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

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 に答える