Heim > Web-Frontend > js-Tutorial > Hauptteil

Wie kann „diese' Referenz in setInterval/setTimeout innerhalb von Prototype-Methoden beibehalten werden?

DDD
Freigeben: 2024-10-18 15:00:05
Original
124 Leute haben es durchsucht

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);
    }
};
Nach dem Login kopieren

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);
Nach dem Login kopieren

Fat Arrow Function Wrapper:

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

setInterval( () => this.baz(), 1000 );
Nach dem Login kopieren

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 );
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonWie kann „diese' Referenz in setInterval/setTimeout innerhalb von Prototype-Methoden beibehalten werden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!