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?
That’s because you lost the value of
thisTry this instead:Explaination, Think of it this way
Now what does
someFunctbelong to?Well try doing
MyObject.prototype.aFunction === MyObject2.prototype.aFunctionit’ll be true!You see the problem Therefore it needs to be called from the class and not just referenced by value.