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 other implications.
Here’s an example of what I’m talking about:
instead of:
var obj = {
key1: "it",
key2: function(){return this.key1 + " works!"}
};
alert(obj.key2());
using:
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
Both can be problematic.
When
funcis not called as a method ofobj,thiscan reference something else (in here: the global object “window“).In here we access the object from another reference, though the
objin the function may now point to some other object.So you will have to choose which case is more likely. If you really want to make it safe, prevent
objfrom being exchanged:or you
bind()the function to the object: