Is it problematic to reference an object literal within a function which is part of that very literal? It seems to work just fine, but I want to make sure there aren\'t othe
Either or both of those techniques may apply depending on the situation.
The value of this
within a function depends on how the function was called. If you call a function as property of an object like this:
obj.key2();
//or
obj["key2"]();
Then this
will be that object. Whether the object was created via an object literal or some other means is not relevant.
But you can use .call() or .apply()
to call a function and explicitly set this
to some other object.
Consider also:
var obj = {
key1: "it",
key2: function(){return this.key1 + " works!"}
};
alert(obj.key2()); // alerts "it works!"
var func = obj.key2;
alert(func()); // alerts "undefined works!"
I'm setting up func
to reference the same function as obj.key2
, but calling it as func()
does not set this
to obj
.
For more information have a look at what MDN has to say about this.