>  기사  >  웹 프론트엔드  >  setInterval 및 setTimeout 내의 프로토타입 메소드에서 이 참조를 유지하는 방법은 무엇입니까?

setInterval 및 setTimeout 내의 프로토타입 메소드에서 이 참조를 유지하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-18 15:05:04142검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.