簡體   English   中英

在對象原型方法中的setInterval / setTimeout內部引用“ this”

[英]Referencing “this” inside setInterval/setTimeout within object prototype methods

通常,在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實現中,可以通過使用fat arrow語法以更簡潔的方式編寫上述解決方案:

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

粗箭頭匿名函數從周圍的函數中保留了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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM