2011-11-01 15 views
0
function test() { 
    this.str = "hello"; 

    this.sayHello = function() { 
     document.write(this.str); 
    } 

    this.init = function() { 
     document.onkeydown = this.sayHello; 
    } 
} 

var testing = new test(); 
testing.init(); 

上記のコードは、onkeydownイベントで "hello"を出力する必要があります。 しかし、私は "未定義"となります。これをどのように機能させることができますか?イベントでオブジェクト変数を取得する

答えて

2

問題はthis.sayHelloです。 keydownのsayHello関数への参照を代入すると、コンテキスト(オブジェクト)への参照が失われます。キーが押されたときのコールバックは次のように呼び出されるよう、thisDocumentオブジェクトを参照:あなたがdocumentオブジェクト上str変数を割り当てた場合は、ログインした値を見ることが

document.onkeydown(); // or for simplicity imagine - document.sayHello(); 

document.str = "hello"; 

しかし、それはあなたが望むものではありません。そのオブジェクトへのコンテキストを保持するために、別の関数の中にkeydownイベントハンドラをラップする必要があります。これについては2つの方法があります。イベントハンドラを別の関数の中にラップし、これへの参照を保持することもできます。

this.init = function() { 
    var me = this; 
    document.onkeydown = function() { 
     me.sayHello(); 
    }; 
} 

それとも、あなたは近代的なブラウザを使用している場合、これはすでにbind機能を使用するECMAScript 5に組み込まれています。

this.init = function() { 
    var me = this; 
    document.onkeydown = this.sayHello.bind(this); 
} 
+0

正確には、私が探していたものです。どうもありがとうございました! –

関連する問題