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

我是研究僧i 提交于 2019-12-25 08:20:07

问题


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);
    }
};

回答1:


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

Wrap the method call inside an anonymous function

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.

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);

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 );

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.

Use a binding function

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);



回答2:


i made a proxy class :)

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);


来源:https://stackoverflow.com/questions/40966223/difference-between-callback-and-callback-in-typescript-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!