Ich habe eine JavaScript-Klasse, und jede Methode gibt eine Q
Versprechen. Ich möchte wissen, warum this
in method2
und method3
nicht definiert ist. Gibt es eine korrektere Möglichkeit, diesen Code zu schreiben?Warum ist 'this' bei der Verwendung von Versprechungen innerhalb der Klassenmethode undefiniert?
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2)
.then(this.method3);
}
MyClass.prototype.method1 = function(){
// ...q stuff...
console.log(this.options); // logs "opts" object
return deferred.promise;
};
MyClass.prototype.method2 = function(method1resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
MyClass.prototype.method3 = function(method2resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
Ich kann dieses Problem beheben, indem bind
mit:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
aber nicht ganz sicher, warum bind
notwendig ist; ist .then()
töten this
aus?
Wenn Sie bind() verwenden, erstellt es eine andere Funktion mit genau dem Umfang, den Sie an Parametern übergeben werden. Obwohl es nur Ihre letzte Frage beantwortet, werfen Sie einen Blick auf die Dokumentation von Mozila: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function/bind –
In 8 Worten, erklären Sie, wie zum Teufel ist das (http://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises) ein Duplikat von [das] (http: // stackoverflow.com/questions/591269/settimeout-and-this-in-javascript)? Ich hatte gerade genau diese Frage kommen, die _not_ von [das] (http://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript) beantwortet worden wäre. Ich kenne [das] (http://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript) bereits, aber ich komme mit Versprechen, ES6-Klassen und 'this' in Einklang. – toszter
Obwohl es eng verwandt ist, ist dies kein Duplikat dieser Frage: http://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript Oder ist "Warum fällt ein Apfel von einem Baum?" ein Duplikat der Frage "Warum bricht ein Kartenhaus zusammen, wenn ich den Tisch kippe, auf dem es gebaut ist?"? – lex82