プロトタイプ メソッド内の setInterval/setTimeout で「this」参照を保持するにはどうすればよいですか?

DDD
リリース: 2024-10-18 15:00:05
オリジナル
125 人が閲覧しました

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!