Reputation: 8582
I have an object in Javascript:
function MyObject(aField) {
this.field = aField;
}
MyObject.prototype.aFunction = function() {
return this.field;
}
Then
var anInstance = new MyObject("blah");
var s = anInstance.aFunction();
this works fine, but if I pass the function to another function:
callLater(anInstance.aFunction);
I don't control callLater
and it's minified, but it seems that it's calling aFunction
using call()
or apply()
. Therefore, this
points to another object and field
is undefined.
What's the best practice to avoid this situation I'm facing?
Upvotes: 0
Views: 50
Reputation: 35284
That's because you lost the value of this
Try this instead:
callLater(function() { anInstance.aFunction() });
Explaination, Think of it this way
function MyObject(aField) {
this.field = aField;
}
function MyObject2(aField) {
this.field = aField;
}
MyObject.prototype.aFunction = someFunct;
MyObject2.prototype.aFunction = someFunct;
Now what does someFunct
belong to?
Well try doing MyObject.prototype.aFunction === MyObject2.prototype.aFunction
it'll be true!
You see the problem Therefore it needs to be called from the class and not just referenced by value.
Upvotes: 2