引用“this”在对象原型方法中的setInterval / setTimeout内 [英] Referencing "this" inside setInterval/setTimeout within object prototype methods
问题描述
通常我会在setInterval中引用this时指定一个替代的self引用。是否有可能在原型方法的上下文中完成类似的事情?以下代码错误。
Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.
function Foo() {}
Foo.prototype = {
bar: function () {
this.baz();
},
baz: function () {
this.draw();
requestAnimFrame(this.baz);
}
};
推荐答案
与像Python这样的语言不同,Javascript方法会忘记它是一种方法,在您提取它并将其传递到其他地方之后。您可以
Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either
这样,访问 baz
属性并同时调用它,这对于在方法调用中正确设置 this
是必要的。
This way, accessing the baz
property and calling it happen at the same time, which is necessary for the this
to be set correctly inside the method call.
你需要在辅助变量中保存外部函数的 this
,因为内部函数将引用一个不同的这个
对象。
You will need to save the this
from the outer function in a helper variable, since the inner function will refer to a different this
object.
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
将方法调用包含在胖箭头函数中
在实现该箭头功能JavaScript实现功能,可以使用胖箭头语法以更简洁的方式编写上述解决方案:
Wrap the method call inside a fat arrow function
In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
胖箭头匿名函数保留此
来自周围的函数所以不需要使用 var = this
技巧。要查看您是否可以使用此功能,请参阅兼容性表格,如这个。
Fat arrow anonymous functions preserve the this
from the surrounding function so there is no need to use the var that = this
trick. To see if you can use this feature, consult a compatibility table like this one.
最后一种方法是使用Function.prototype等函数.bind或您喜欢的Javascript库中的等价物。
A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);
这篇关于引用“this”在对象原型方法中的setInterval / setTimeout内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!