関数のスコープは、OOJS の難しい問題の 1 つです。重要なのは、オブジェクト メソッドは objectのプロパティとして割り当てられた単なる関数であることを覚えておくことです。そのため、慎重に呼び出されない場合 (たとえば、何かへのコールバックとして渡される場合)、間違ったコンテキストで実行される可能性があります。this
あなたが発見しているように、間違ったものが にバインドされています。
次のことを覚えておいてください。
var someObj = {
someMethod: function() {
}
}
someObj.someMethod(); // in someMethod, this will be someObj
var someRef = someObj.someMethod;
someRef(); // the function will now run with this bound to the window object, which you probably don't want
参照を渡す必要がある場合は、関数をバインドできます。最新のブラウザーでは、次を使用できますFunction.prototype.bind
。
this.aProperty = (function() {}).bind(this);
古いブラウザにはポリフィルが必要です。jQuery には次の 1 つがあります。
this.aProperty = $.proxy(function() { }, this);
または、独自に記述することもできます。
Function.prototype.bind = function(scope) {
var fn = this;
return function() {
fn.apply(scope, arguments);
}
}
.bind
最初の例のような構文を使用します。