How To Use Properties Of An Object Literal Without Being Inside A Function In Javascript
Solution 1:
You can't refer to the "object being defined" in an object literal. That is, there's no way to have the value expression for a property of the under-construction object refer to the object itself in order to access another (presumably, already-defined) property.
You can however add a property to the object after it's been defined.
varobj= { a:0 };obj.b=(obj.a?1 :2);
Or in your case:
var settings = { ... };
settings.inDent = ($(settings.slides).find('li').outerWidth());
Solution 2:
You need to use
this.inDent
The inDent
field would be accessed via settings.inDent
only outside of the settings
object definition
Solution 3:
Use closures, e.g
var settings = function(){
varprivate = {};
private.slides = '#slides';
varpublic = {}
public.inDent = ($(private.slides).find('li').outerWidth());
public.doSomething = function(){
console.log( public.inDent );
}
returnpublic;
}();
The advantage of this is also that it gives you "encapsulation" for free
BTW, you shouldn't rely on anything that is publicly available, because, well, it can be changed, e.g. settings.inDent = null
and then settings.doSomething()
may no longer function correctly. What correct way to do it is the following
...
private.inDent = ($(settings.slides).find('li').outerWidth());
public.inDent = private.inDent;
public.doSomething = function(){
console.log( private.inDent );
}
i.e. make the inDent
value "read only" (in a sense that nothing outside of the settings
object can actually change the internal implementation of private.inDent
); as long as you always use private.inDent
from within settings
you're safe because even if someone does settings.inDent = null
, the settings.doSomething();
will still function properly
Post a Comment for "How To Use Properties Of An Object Literal Without Being Inside A Function In Javascript"