2012-02-13 5 views
1

だが、私はこのようなJavaScriptのクラスを持っているとしましょう:JavaScriptのイベントハンドラにオブジェクト機能への対応

Foo.prototype = { 
    init: function() { 
    $(document).keydown(function(event) { 
     this.onKeyDown(event); 
    }); 
    } 

    onKeyDown: function(event) { 
    alert("bar"); 
    } 
} 

myObj = new Foo(); 
myObj.init(); 

このコードは動作しません、なぜなら

$(document).keydown(function(event) { 
    this.onKeyDown(event); 
}); 

で "これはもちろん不明であり、オブジェクトに対処しません。私はどのようにしてFoo-Classのonkeydown-methodに対処できますか?

私はこのクラスを他のオブジェクトにも使いたいので、 'myObj'(オブジェクトの名前)と交換する必要はありません。

ありがとうございました!

答えて

4

ストア、それを変数で...

Foo.prototype = { 
    init: function() { 
    var self = this 
    $(document).keydown(function(event) { 
     self.onKeyDown(event); 
    }); 
    } 
} 

またはバインドthis値を持つ関数を返すためにjQuery.proxyを使用して...

Foo.prototype = { 
    init: function() { 
    $(document).keydown($.proxy(function(event) { 
     this.onKeyDown(event); 
    }, this)); 
    } 
} 

か、Function.prototype.bindを使用することができますが、あなたの」古いブラウザ用にパッチを適用する必要があります。 .bind() ためのMDNから

Foo.prototype = { 
    init: function() { 
    $(document).keydown((function(event) { 
     this.onKeyDown(event); 
    }).bind(this)); 
    } 
} 
関連する問題