Reputation: 5390
Is there a difference between the 2 code snippets?
Since foo
is a member function of obj
, this
would refer to obj
itself (method invocation pattern).
1.
var obj = {};
obj.prop = some_property;
obj.foo = function() {
do_something_with(obj.prop);
};
2.
var obj = {};
obj.prop = some_property;
obj.foo = function() {
do_something_with(this.prop);
};
An application I was working on, kept crashing when I used approach 2.
The code was something like :
obj = {};
obj.listener = {
eventprocess : function(param) {
//some code
}
};
obj.init = function() {
this.a = library_func();
this.a.add_listener(this.listener);
};
it worked when I used approach 1.
Any ideas why?
Upvotes: 1
Views: 167
Reputation: 75327
As the resolution of obj
and this
is deferred until execution of the function, it's result can vary depending on whether this
or/and obj
has changed between definition and invocation.
For example, given two objects which are identical, except one uses this
and the other uses obj
in the function foo
:
var objA = {};
objA.prop = "test";
objA.foo = function() {
alert(this.prop);
};
var objB = {};
objB.prop = "test";
objB.foo = function() {
alert(objB.prop);
};
... we'll see different behavior here:
var anotherObject = {
objAFoo: objA.foo,
objBFoo: objB.foo
};
anotherObject.objAFoo(); // "undefined";
anotherObject.objBFoo(); // "test";
Note that you can normalize this behavior by setting the value of this
using call()
or apply()
, as pointed out in the comments:
anotherObject.objAFoo.call(objA); // "test";
However, note also that cases where this
has been bound using bind()
or jQuery.proxy()
can hurt you here.
Upvotes: 2