我正在Windows上使用带有harmony
标志的node v0.11.14-nightly-20140819-pre。
我的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);
}
Service
对象的 serviceMethod
方法返回一个 Promise。当我像下面这样使用 User
对象:
let user = new User(args);
user.method1();
then
方法在Promise对象被解决后调用User
对象的method2
方法时,this
变为undefined
。我尝试了ES6和Bluebird两种Promise实现方式。
为什么在这种情况下this
会变成undefined
呢?