引用“this"在对象原型方法中的 setInterval/setTimeout 内部 [英] Referencing "this" inside setInterval/setTimeout within object prototype methods

查看:18
本文介绍了引用“this"在对象原型方法中的 setInterval/setTimeout 内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在 setInterval 中引用this"时,我会分配一个替代的self"引用.是否有可能在原型方法的上下文中完成类似的事情?以下代码错误.

function Foo() {}Foo.prototype = {酒吧:功能(){this.baz();},巴兹:函数(){this.draw();requestAnimFrame(this.baz);}};

解决方案

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

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

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

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

var that = this;设置间隔(函数(){返回 that.baz();}, 1000);

将方法调用包裹在一个粗箭头函数中

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

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

胖箭头匿名函数将 this 从周围的函数中保留下来,因此无需使用 var that = this 技巧.要查看您是否可以使用此功能,请查阅兼容性表,例如 this one.

使用绑定函数

最后一种选择是使用函数,例如 Function.prototype.bind 或您最喜欢的 Javascript 库中的等效函数.

setInterval( this.baz.bind(this), 1000 );//dojo 工具包示例:setInterval( dojo.hitch(this, 'baz'), 100);

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

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

这篇关于引用“this"在对象原型方法中的 setInterval/setTimeout 内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆