Sto utilizzando nodo v0.11.14-nightly-20140819-pre su Windows con flag harmony
.Metodo oggetto con ES6/Bluebird promette
devo oggetto JavaScript con due metodi definiti nel suo prototipo:
function User (args) {
this.service= new Service(args);
}
User.prototype.method2 = function (response) {
console.log(this); // <= UNDEFINED!!!!
};
User.prototype.method1 = function() {
.............
this.service.serviceMethod(args)
.then(this.method2)
.catch(onRejected);
};
function onRejected(val) {
console.log(val);
}
serviceMethod
di Service
oggetto restituisce una promessa.
quando uso User
oggetto come il seguente:
let user = new User(args);
user.method1();
this
in method2
dell'oggetto User
finisce undefined
quando viene chiamato da then
una volta promessa si compie.
Ho provato ad utilizzare sia Bluebird implementazione promessa ES6 e .
Perché this
in questo caso è undefined
?
questo è quello che ho finito per fare per mantenere le cose compatibili con ES6 promette – krl
Ho finito per usare questo soluzione e sintassi di freccia grossa per i casi in cui avere un metodo prototipo separato era troppo prolisso. Credo che entrambi siano compatibili ES6 +. – Tom