【发布时间】:2015-01-24 18:34:41
【问题描述】:
我在带有harmony 标志的 Windows 上使用 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);
}
serviceMethod 的 Service 对象返回一个承诺。
当我使用User 对象时,如下所示:
let user = new User(args);
user.method1();
method2 对象 User 中的this 在被 then 调用时,一旦实现承诺,就会结束 undefined。
我尝试同时使用 ES6 和 Bluebird 承诺实现。
在这种情况下,为什么 this 最终会变成 undefined?
【问题讨论】:
标签: javascript node.js promise bluebird