Huc*_*uck 32 javascript scope lexical-scope
通常我会在setInterval中引用"this"时指定一个替代的"self"引用.是否有可能在原型方法的上下文中完成类似的事情?以下代码错误.
function Foo() {}
Foo.prototype = {
bar: function () {
this.baz();
},
baz: function () {
this.draw();
requestAnimFrame(this.baz);
}
};
Run Code Online (Sandbox Code Playgroud)
hug*_*omg 66
与Python之类的语言不同,Javascript方法会在您将其提取并将其传递到其他位置后忘记它.你也可以
这样,访问baz属性并同时调用它,这是this在方法调用中正确设置所必需的.
您需要this将外部函数保存在辅助变量中,因为内部函数将引用另一个this对象.
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
Run Code Online (Sandbox Code Playgroud)
在实现箭头函数功能的Javascript实现中,可以使用胖箭头语法以更简洁的方式编写上述解决方案:
setInterval( () => this.baz(), 1000 );
Run Code Online (Sandbox Code Playgroud)
胖箭头匿名函数保留了this周围的函数,因此不需要使用该var that = this技巧.要查看是否可以使用此功能,请参阅此类兼容性表.
最后一种方法是使用Function.prototype.bind等函数或您喜欢的Javascript库中的等效函数.
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);
Run Code Online (Sandbox Code Playgroud)