在对象原型方法中的setInterval / setTimeout内引用“this”

通常我会在setInterval中引用“this”时指定另一个“self”引用。 是否有可能在原型方法的背景下完成类似的事情? 以下代码错误。

function Foo() {} Foo.prototype = { bar: function () { this.baz(); }, baz: function () { this.draw(); requestAnimFrame(this.baz); } }; 

与Python之类的语言不同的是,一种方法在将其提取出来并传递给某个方法后,会忘记它的一种方法。 你也可以

将方法调用封装在一个匿名函数中

这样,访问baz属性并同时调用它,这是在方法调用中正确设置的必要条件。

由于内部函数与外部不同,因此需要使用辅助variables。

 var that = this; setInterval(function(){ return that.baz(); }, 1000); 

将方法调用封装在胖箭头函数中

一些Javascript实现支持箭头函数 ,它们是从外部函数inheritance“this”的匿名函数。 如果您可以使用这个ES6function,则可以使以前的解决scheme更加简洁一些:

 setInterval( () => this.baz(), 1000 ); 

使用绑定function

最后一种select是使用Function.prototype.bind之类的函数,或者使用您最喜欢的Javascript库中的等效函数。

 setInterval( this.baz.bind(this), 1000 ); //dojo toolkit example: setInterval( dojo.hitch(this, 'baz'), 100); 

我做了一个代理类:)

 function callback_proxy(obj, obj_method_name) { instance_id = callback_proxy.instance_id++; callback_proxy.instances[instance_id] = obj; return eval('fn = function() { callback_proxy.instances['+instance_id+'].'+obj_method_name+'(); }'); } callback_proxy.instance_id = 0; callback_proxy.instances = new Array(); function Timer(left_time) { this.left_time = left_time; //second this.timer_id; this.update = function() { this.left_time -= 1; if( this.left_time<=0 ) { alert('fin!'); clearInterval(this.timer_id); return; } } this.timer_id = setInterval(callback_proxy(this, 'update'), 1000); } new Timer(10);