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

Referencing "this" inside setInterval/setTimeout within object prototype methods

本文关键字:方法 setInterval setTimeout 原型 对象 this quot 引用      更新时间:2023-09-26

通常,当在setInterval中引用"this"时,我会指定一个替代的"self"引用。是否有可能在原型方法的上下文中完成类似的事情?下面的代码出错。

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

与Python等语言不同,Javascript方法在提取它并将其传递到其他地方后会忘记它是一个方法。

将方法调用包装在匿名函数中

这样,访问baz属性和调用它同时发生,这对于在方法调用中正确设置this是必要的。

您需要将外部函数中的this保存在辅助变量中,因为内部函数将引用不同的this对象。

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

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

在实现箭头函数特性的Javascript实现中,可以通过使用胖箭头语法以更简洁的方式编写上述解决方案:

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

Fat arrow匿名函数将this与周围函数保持一致,因此不需要使用var that = this技巧。要查看是否可以使用此功能,请参考如下的兼容性表。

使用绑定函数

最后一种选择是使用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);