带有 ES6/Bluebird 承诺的对象方法 [英] Object method with ES6 / Bluebird promises
问题描述
我在带有 harmony
标志的 Windows 上使用 node v0.11.14-nightly-20140819-pre.
I am using node v0.11.14-nightly-20140819-pre on Windows with harmony
flag.
我有一个 JavaScript 对象,它的原型中定义了两个方法:
I have JavaScript object with two methods defined in its 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.
serviceMethod
of Service
object returns a promise.
当我使用 User
对象时,如下所示:
When I use User
object like below:
let user = new User(args);
user.method1();
对象User
的method2
中的
this
在被then
调用时以undefined
结束> 一旦兑现承诺.
this
in method2
of object User
ends up undefined
when called by then
once promise is fulfilled.
我尝试同时使用 ES6 和 Bluebird 承诺实现.
I tried using both ES6 and Bluebird promise implementation.
为什么在这种情况下 this
最终是 undefined
?
Why this
ends up being undefined
in this case?
推荐答案
为什么在这种情况下
this
最终是undefined
?
因为您传递的是函数,而不是绑定到实例的方法.这个问题甚至不是特定于 promise 的,请参见 如何在回调中访问正确的 `this` 上下文?解决方案:
Because you're passing a function, not a method-bound-to-an-instance. This problem is not even promise-specific, see How to access the correct `this` context inside a callback? for the generic solution:
….then(this.method2.bind(this))… // ES5 .bind() Function method
….then((r) => this.method2(r))… // ES6 arrow function
但是,Bluebird 确实提供 将函数作为方法调用的另一种方式:
However, Bluebird does offer an other way to call the function as a method:
this.service.serviceMethod(args)
.bind(this)
.then(this.method2)
.catch(onRejected);
这篇关于带有 ES6/Bluebird 承诺的对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!