ES6 / Bluebird承诺的对象方法 [英] Object method with ES6 / Bluebird promises
问题描述
我在Windows上使用节点v0.11.14-nightly-20140819-pre harmony
flag。
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);
}
serviceMethod
of 服务
对象返回一个承诺。
serviceMethod
of Service
object returns a promise.
当我使用用户
对象如下:
let user = new User(args);
user.method1();
此
in 对象
在的method2
用户调用时结束
一旦履行承诺。 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.
为什么这个
在这种情况下最终是 undefined
?
Why this
ends up being undefined
in this case?
推荐答案
为什么
此
最终为undefined
在这种情况下?
Why
this
ends up beingundefined
in this case?
因为你传递了一个函数,而不是一个方法绑定到一个实例。此问题甚至不是特定于承诺的,请参阅如何在回调中访问正确的`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屋!