Settimeout, bind und dieses
Hier habe ich Code-Snippet von MDN kopiert:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bin
function LateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom();
// after 1 second, triggers the 'declare' method
er verwirrendste Teil ist:window.setTimeout(this.declare.bind(this), 1000);
Ich verstehe, wiethis
works undthis
inside settimeout ist immer an ein globales Objekt gebunden. Ich weiß, dass es @ geben kanvar self odervar that Inside Bloom Funktion.
Es gibt zweithis
in dieser Zeile aber welchethis
bezieht sich auf was und wie das funktioniert ist total verwirrend.
Wie funktioniert das?