我在带有 harmony
标志的 Windows 上使用 node v0.11.14-nightly-20140819-pre。
我的 JavaScript 对象在其原型(prototype)中定义了两个方法:
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);
}
Service
对象的serviceMethod
返回一个promise。
当我使用 User
对象时,如下所示:
let user = new User(args);
user.method1();
对象 User
的 method2
中的 this
在被 then
调用时以 undefined
结束> 一旦 promise 兑现。
我尝试同时使用 ES6 和 Bluebird promise 实现。
为什么 this
在这种情况下会变成 undefined
?
最佳答案
Why
this
ends up beingundefined
in this case?
因为您传递的是函数,而不是方法绑定(bind)到实例。这个问题甚至不是特定于 promise 的,请参阅 How to access the correct `this` context inside a callback?对于通用解决方案:
….then(this.method2.bind(this))… // ES5 .bind() Function method
….then((r) => this.method2(r))… // ES6 arrow function
但是,Bluebird does offer将函数作为方法调用的另一种方式:
this.service.serviceMethod(args)
.bind(this)
.then(this.method2)
.catch(onRejected);
关于javascript - 带有 ES6/Bluebird promise 的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27149034/