首页 > web前端 > js教程 > 正文

如何在 setInterval 和 setTimeout 内的原型方法中维护此引用?

Patricia Arquette
发布: 2024-10-18 15:05:04
原创
142 人浏览过

How to Maintain This Reference in Prototype Methods within setInterval and setTimeout?

Using this within Prototype Methods in setInterval and setTimeout

When using setInterval or setTimeout, it's essential to maintain a reference to the correct this context inside prototype methods. However, referencing this in these situations can be tricky.

The Problem

For example, consider the following code:

<code class="javascript">function Foo() {}
Foo.prototype = {
    bar: function () {
        this.baz();
    },
    baz: function () {
        this.draw();
        requestAnimFrame(this.baz);
    }
};</code>
登录后复制

In this code, an attempt is made to use this to refer to the Foo instance within the prototype method baz. However, this code throws an error because after extracting the method call and passing it to requestAnimFrame, the method loses its reference to this.

The Solution

There are several ways to overcome this issue:

Using an Anonymous Function

One solution is to wrap the method call within an anonymous function:

<code class="javascript">var that = this;
setInterval(function(){
    return that.baz();
}, 1000);</code>
登录后复制

In this approach, the this context is saved in the that variable, ensuring correct access to it within the anonymous function's scope.

Using a Fat Arrow Function

If your JavaScript implementation supports fat arrow functions, you can use them to simplify the code:

<code class="javascript">setInterval( () =&gt; this.baz(), 1000 );</code>
登录后复制

Fat arrow functions preserve the this context of the surrounding function, eliminating the need for a helper variable.

Using a Binding Function

Finally, you can also use a binding function like Function.prototype.bind to set the this context explicitly:

<code class="javascript">setInterval( this.baz.bind(this), 1000 );</code>
登录后复制

These alternative solutions allow you to maintain the correct this reference within your prototype methods when used with setInterval or setTimeout.

以上是如何在 setInterval 和 setTimeout 内的原型方法中维护此引用?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!