Javascript:クラスの関数の1つ内の関数からクラス属性にアクセスする方法

StackOverflow https://stackoverflow.com/questions/429487

  •  06-07-2019
  •  | 
  •  

質問

クラスの特定の関数内で、 setInterval を使用してコードの実行を分割する必要があります。ただし、 setInterval 関数内では、" this"クラス「myObject」を参照しなくなりました。変数" name"にアクセスするにはどうすればよいですか? setInterval 関数内からですか?

function myObject() {
    this.name = "the name";
}

myObject.prototype.getName = function() {
    return this.name;
}

myObject.prototype.test = function() {
    // this works
    alert(this.name);

    var intervalId = setInterval(function() {
        // this does not work
        alert(this.name);

        clearInterval(intervalId);
    },0);
}
役に立ちましたか?

解決

myObject.prototype.test = function() {
    // this works
    alert(this.name);
    var oThis = this;
    var intervalId = setInterval(function() {
        // this does not work
        alert(oThis.name);

        clearInterval(intervalId);
    },0);
}

これは動作するはずです。無名関数の" this"同じではない「これ」 myObjectの「this。」として

他のヒント

これはプロトタイプバインド関数です

Function.prototype.bind = function( obj ) {
    var _this = this;
    return function() {
        return _this.apply( obj, arguments );
    }
}

これは、Prototypeでのバインディングの目的です:

function myObject() {
    this.name = "the name";
}

myObject.prototype.getName = function() {
    return this.name;
}

myObject.prototype.test = function() {
    // this works
    alert(this.name);

    var intervalId = setInterval(function() {
        // this does not work
        alert(this.name);

        clearInterval(intervalId);
    }.bind(this),0);
}

bind()は標準機能ではなく、他の場所で提供する必要があるため、s13jamesの答えは不完全であることに注意してください。自分でmeouwのコード例を使用します。

bind()(これは気の利いたことです、私は言わなければなりません)を使用しない場合、djangelの応答はあなたができたはずのことであり、私が最も頻繁に行うことです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top