我在带有标志的Windows上使用节点v0.11.14-nightly-20140819-preharmony
。
我的JavaScript对象在其原型中定义了两种方法:
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
的Service
对象返回一个承诺。
当我使用User
如下对象时:
let user = new User(args);
user.method1();
this
在method2
对象的User
结束undefined
时,由被称为then
一旦承诺得到满足。
我尝试同时使用ES6和Bluebird promise实现。
为什么this
最终会undefined
出现这种情况?
为什么
this
最终会undefined
出现这种情况?
因为您传递的是函数,而不是方法绑定的实例。这个问题甚至不是特定于Promise的,请参阅如何在回调中访问正确的`this`上下文?对于通用解决方案:
….then(this.method2.bind(this))… // ES5 .bind() Function method
….then((r) => this.method2(r))… // ES6 arrow function
但是,Bluebird确实提供了另一种方法来调用函数:
this.service.serviceMethod(args)
.bind(this)
.then(this.method2)
.catch(onRejected);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句