次のコードがあります。
object.waypoint=function () {
this.uw=setInterval( function() {
console.log(this);
}, 200);
}
3行目の関数内で「object」を参照するにはどうすればよいですか。「this」キーワードで試してみましたが、オブジェクトを参照していないようです。
次のコードがあります。
object.waypoint=function () {
this.uw=setInterval( function() {
console.log(this);
}, 200);
}
3行目の関数内で「object」を参照するにはどうすればよいですか。「this」キーワードで試してみましたが、オブジェクトを参照していないようです。
setInterval内this
はウィンドウを参照します。を参照する変数を作成する必要がありますthis
。
object.waypoint=function () {
var me = this;
this.uw=setInterval( function() {
console.log(me);
}, 200);
}
一般的な方法は、への参照を変数に格納することです。これを使用して、適切な: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);
}