Perché non lo passa. MetodOD come un parametro funziona?
-
21-12-2019 - |
Domanda
In una classe che rappresenta una richiesta, cerco di elaborarla con le promesse q e, dopo che hanno due semplici gestori per inviare il risultato dell'elaborazione.Perché questo non funziona:
Request.prototype.process = function() {
var that = this;
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(that.replyOK)
.fail(that.replyError);
};
.
Ma questo fa:
Request.prototype.process = function() {
var that = this;
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(function(error) {
that.replyOK(error);
})
.fail(function(error) {
that.replyError(error);
});
};
. Soluzione
JavaScript è per lo più schermato lessicamente.Ciò significa che in:
function foo(){
var that = this;
//...
}
.
Le variabili che accedono che nelle seguenti righe di foo that
è impostata su ciò che ti aspetti.Se si passano le funzioni con i locali definiscono altrove, that
non verrà acquisito nel loro ambiente lessicale (variabile).
JavaScript ha anche this
dinamico, il this
di un metodo è determinato dall'oggetto attualmente chiamato.Ad esempio:
var a = {
x:3,
getX:function(){ return this.x; }
};
var b = {x:5};
b.getX = a.getX;
b.getX(); // returns 5
a.getX(); // returns 3
a.getX.call(b); // set `this` explicitly with .call, returns 5
var x = a.getX;
x(); // global x or undefined.
.
È possibile riparare this
utilizzando Function.prototype.bind
in quanto tale:
Request.prototype.process = function() {
return this.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(this.replyOK.bind(this))
.fail(this.replyError.bind(this));
};
.
o, in ECMAScript 6 Sintassi (non disponibile ancora nel nodo, ma presto):
Request.prototype.process = () => { // arrow functions have lexical `this`
return that.getParameter('method')
.then(function(method) {
// ... Some processing
})
.then(this.replyOK)
.fail(this.replyError);
};
.