1

次のコードがあります。

object.waypoint=function () {
    this.uw=setInterval( function() {
       console.log(this);
    }, 200);
}

3行目の関数内で「object」を参照するにはどうすればよいですか。「this」キーワードで試してみましたが、オブジェクトを参照していないようです。

4

3 に答える 3

1

setInterval内thisはウィンドウを参照します。を参照する変数を作成する必要がありますthis

object.waypoint=function () {
    var me = this;

    this.uw=setInterval( function() {
       console.log(me);
    }, 200);
}
于 2012-11-14T13:40:32.150 に答える
1

一般的な方法は、への参照を変数に格納することです。これを使用して、適切な:thisにアクセスできます。this

object.waypoint=function () {
    // Keep a reference to this in a variable
    var that = this;
    that.uw=setInterval( function() {
       // Now you can get access to this in here as well through the variable
       console.log(that);
    }, 200);
}
于 2012-11-14T13:41:15.557 に答える
0

bindはそれがきちんとした解決策だと思います-それはすべてのブラウザに実装されているわけではありませんが、回避策があります。

object.waypoint = function(){
    this.uw = setInterval(function(){
        console.log(this);
    }.bind(this), 200);
}

適切なドキュメントについては、 MDNページを参照してください

于 2012-11-14T14:59:25.493 に答える