0

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?

4

1 回答 1

2

那是因为你失去了thisTry this 的价值:

callLater(function() { anInstance.aFunction() });

解释,这样想

function MyObject(aField) {
    this.field = aField;
}
function MyObject2(aField) {
    this.field = aField;
}
MyObject.prototype.aFunction = someFunct;
MyObject2.prototype.aFunction = someFunct;

现在someFunct属于什么?

好吧,尝试这样做MyObject.prototype.aFunction === MyObject2.prototype.aFunction会是真的!

您会看到问题因此需要从类中调用它,而不仅仅是通过值引用。

于 2012-08-17T20:46:18.370 回答