Shortcut for accessing object attributes in javascript - javascript

I have a model object with a property called definition that i am using across a class. I can access that property like model.attributes.definition
Every time that i want to use this property inside a method, and for the sake of clarity, i am creating a shortcut definition = model.attributes.definition at the very beggining so the method code does not get populated with boilerplate.
Because i am using it across several methods i thought that, instead of creating the shortcut on every method, i could create a little helper function to do the job:
getDefinition: (model) ->
model.attributes.definition
and then use it anywhere like
if getDefinition(model).name?
doSomething()
But aren't these function calls across my code innecessary/resource consuming for such a trivial task? What is a good approach in a situation like this?

You can also access object values via string:
definition = "attributes.definition"
then to access the value:
if model[definition].name?
doSomething()

Related

Does it make diffrence in speed efficiency of code if we assign property of object to another variable and then use it?

I wonder does it make difference if I use another variable to access the property of object once and for all or access the data that I want , from the object each time :
data = {position: [{X:12},{Y:4}] ,name : 'Smth'}
is there any diffrent between the following method :
const X = data.position[0].X
for(...){
...do somthing with X
}
or
for(...){
...do somthing with data.position[0].X
}
Yes, some different is exist. Every time when you call property js interpreter try to find calling property (or method) at prototype hierarchy.
Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.
If you use variable to cache some data it will be faster than you use direct access.
There is some great benchmark to test it.

Haxe Javascript: Prevent '$bind' generation?

Is there a simple way to prevent $bind generation when passing around class member functions?
I have an object that takes in a function which will be called in an arbitrary interval. The object always binds itself as the 'this' binding before calling the function (this is done in the native side), therefore the call to $bind itself is unnecessary. However, I can't seem to find a simple way to prevent $bind from being emitted any time I grab a member function by value.
The only way I've found is to use __js__ with a string literal of the member function name, which I would rather avoid... Is there a typed way to do so? Or something a bit nicer? A way to still use haxe syntax w/ identifiers instead of a string literal?
Example:
private function onSpawn():Void
{
this.setAct( act ); // Will generate JS: this.setAct($bind(this,this.act));
// Id like to simply have it generate: this.setAct( this.act );
// Mitigated like this:
this.setAct( untyped __js__("this.act") );
}
private function act( dt:Float ):Void
{
...
}
Thank you.
You use macro to mask out the untyped expression, but this is quite dangerous.
Any reference to "this" will fail.
http://try-haxe.mrcdk.com/#70ee4
Btw, I think the compiler may be optimized to not generate $bind if the function code doesn't involve "this". You may want to raise an issue in the github repo about that.

How to obtain true de-referenced object instances in javascript

I'm trying to get a better understanding of object oriented patterns in JavaScript. I particulary like the way EmberJS implements their classes with .extend and .create from Parent class Objects.
I've tried to implement a basic version of this on my own, but to no success, my newly instantiated Objects reference the same Object. I.e If I increment a private counter var in instance a via a public method, then separately do the same to instance b, b will reflect both increments.
I was able to achieve a de-referenced object via Object.create(myClass), however this is undesirable as I'd like to achieve this internally and also not rely on client support for that native method.
Here's a jsbin of what I've got: http://jsbin.com/zepaju/6/edit?js,console
Thanks for any help!
This is a pretty big subject, because there isn't a perfect way to make JavaScript work like Java-- you'll always have to invent some new coding idiom, and different people have different preferences.
Looking at your linked code, it's hard to be sure what you're gunning for but it looks like the problem is that you're thinking of an object's prototype as a "class", which is copied into each "instance" (like in Java)-- this isn't the case.
Your create() function is creating each "instance" by doing Object.create(Poll), which makes a new object with the Poll object as its prototype. When you refer to properties of the resulting objects, and those properties are not directly defined on the object, what you get is a reference to a property of the single Poll object.
The fact that you've sealed the Poll object's internal variables within a closure doesn't make any difference to this; the closure variables are hidden from the outside world, but they are accessible to the methods of the Poll object, and those methods are shared between all "instances".
If you want a function that spits out objects with a particular set of methods, and which hide their internal data in a closure, that might look like:
function Poll(challenger,incumbent) {
var challengerVotes=0;
var incumbentVotes=0;
return {
voteForChallenger: function() {challengerVotes++},
voteForIncumbent: function() {incumbentVotes++},
winner: function() {return challengerVotes>incumbentVotes ? challenger : incumbent}
}
}
var poll1 = Poll("Edward","Jacob");
var poll2 = Poll("Vanilla","Stilton");
poll1 and poll2 would not affect one another, and there would be no way to access the vote counts of either except through the supplied methods. I appreciate you're looking for a more generic approach but this is an example of how you might start.

jQuery like custom functions

I have been wondering how I can create functions like jQuery. For example: $(ID).function()
Where ID is the id of an HTML element, $ is a function that return the document.getElementById reference of the element "ID" and function is a custom javascript function.
I'm creating a little library which implements some functions. And I want to use that sintax without using jQuery.
Now, my questions are: how I can implement that? What is the name of the tecnique that allow that?
Edit:
What I want to do is this:
HTMLElement.prototype.alertMe = function() {alert(this.value);}
Then, when I call document.getElementById('html_input_id').alertMe(), it must show an alertbox with the input value. But HTMLElement.prototype doesn't work in IE.
$ = function(id) {
return document.getElementById(id);
}
Okay, look, what you're asking has a lot of details and implications. The code for jQuery is open source, you can read it for the details; you'd do well to find a good Javascript book as well, the the O'Reilly Definitive Guide.
$ is just a character for names in JS, so as some of the other answers have shown, there's no reason you can't just write a function with that name:
var $ = function(args){...}
Since everyone and his brother uses that trick, you want to have a longer name as well, so you can mix things.
var EstebansLibrary = function(args){...}
var $ = EstebansLibrary; // make an alias
Since you end up doing different things with the entry point function, you need to know how JS uses arguments -- look up the arguments object.
You'll want to package this so that your internals don't pollute the namespace; you'll want some variant of the module pattern, which will make it something like
var EstebansLibrary = (function(){
// process the arguments object
// do stuff
return {
opname : implementation,...
}
})();
And you'll eventually want to be prepared for inheritance and that means putting those functions into the prototype object.
You can use prototype to assign a new function to the Element prototype.
Element.prototype.testFunction=function(str){alert(str)};
This would provide the function 'testFunction' to all HTML elements.
You can extend any base Object this way, i.e. Array, String etc.
This will work without any plugin at all - although that said I don't think it will work in IE. I believe libraries such as MooTools and jQquery create their own inheritance with DOM elements to ensure cross-browser compatibility, although don't quote me on that.

JQuery - Extend and Access Superclass

Is there a way to access the super object when extending objects using $.extend?
I would like to extend an object, override a method, but call the overridden superclass method in the subclass method.
No, because there is no superclass. According to the docs for jQuery.extend:
Description: Merge the contents of two or more objects together into the first object.
In order to call a "superclass" method, you would have to keep a copy of the "superclass" around somewhere (perhaps as a parameter in the "descendant" object), and call the method directly on the "superclass".
If you are looking for javascript inheritance, you may be interested in this post from John Resig.
Not directly -- the old method is not longer around (except in the original object).
I've done two things: The first is to make a copy of the old method with a new name in the subclass:
var Super = {
a: function() {...}
};
var _SubFuncs: {
_superA: Super.a
a: function() {... this._superA(...) ... }
};
var Sub = $.extend(false, Super, _SubFuncs);
The other thing I've done when appropriate is to use the template pattern and have the super class call a method that for it has no behavior. The subclass then add behavior to the empty method. This only works if your call structure is such that "holes" can be added appropriately.
Edit: In my case, I was really trying to stick with prototypal objects so I was avoiding a general solution that makes my objects more class-like.
If you want to use the class inheritance and call the super class methods, then this blog from John Resig explains it all http://ejohn.org/blog/simple-javascript-inheritance/

Categories

Resources