JavaScript で setTimeout/setInterval を使用する場合、プロトタイプ メソッドで「この」コンテキストを保持するにはどうすればよいですか?

Mary-Kate Olsen
リリース: 2024-10-18 15:02:30
オリジナル
523 人が閲覧しました

How Can I Preserve \

Preserving "this" Context in Prototype Methods with setTimeout/setInterval

In Javascript, accessing "this" within a prototype method can become tricky when using setTimeouts or intervals. Unlike in Python, Javascript methods lose their context when passed externally. To overcome this challenge, we explore various solutions.

Anonymous Function Wrapper

The most straightforward approach is to wrap the method call in an anonymous function:

<code class="javascript">var that = this;
setInterval(function(){
    return that.baz();
}, 1000);</code>
ログイン後にコピー

This ensures that the method call and access to "this" occur simultaneously, preserving the correct context.

Fat Arrow Function Wrapper (ES6)

For implementations supporting fat arrow functions:

<code class="javascript">setInterval( () =&gt; this.baz(), 1000 );</code>
ログイン後にコピー

This concise syntax preserves the context from the surrounding function.

Function Binding

Finally, consider using a binding function like Function.prototype.bind:

<code class="javascript">setInterval( this.baz.bind(this), 1000 );</code>
ログイン後にコピー

Alternatively, libraries like Dojo provide methods like "hitch" for context binding.

以上がJavaScript で setTimeout/setInterval を使用する場合、プロトタイプ メソッドで「この」コンテキストを保持するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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