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

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

DDD
DDD원래의
2024-10-18 15:00:05126검색

How to Preserve \

Referencing "this" within setInterval/setTimeout in Prototype Methods

While typically, assigning an alternative "self" reference is used to refer to "this" within setInterval, this method may not be feasible for prototype methods. For instance, in the following code:

function Foo() {}
Foo.prototype = {
    bar: function () {
        this.baz();
    },
    baz: function () {
        this.draw();
        requestAnimFrame(this.baz);
    }
};

This code encounters an error because the method call to baz is taken out of context and loses its "this" reference. To resolve this issue, consider the following alternatives:

Anonymous Function Wrapper:

Wrap the method call within an anonymous function to ensure it is called immediately after accessing the baz property, preserving the correct "this" context. However, a helper variable is necessary to store the "this" reference from the outer function.

var that = this;
setInterval(function(){
    return that.baz();
}, 1000);

Fat Arrow Function Wrapper:

If arrow functions are supported, this issue can be addressed more concisely:

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

Binding Function:

Utilize a binding function like Function.prototype.bind or its equivalent from a preferred library to preserve the "this" reference:

setInterval( this.baz.bind(this), 1000 );

위 내용은 프로토타입 메소드 내에서 setInterval/setTimeout의 \"this\" 참조를 유지하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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