对象方法与ES6 /蓝鸟承诺
我使用harmony
标志在Windows上使用节点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();
this
在对象的方法2中User
一旦被调用一旦被调用then
结束了undefined
。
我试过使用ES6和蓝鸟承诺实施。
为什么最终在这种情况下undefined
?
为什么最终在这种情况下
undefined
?
因为你正在传递一个函数,而不是一个方法绑定的实例。 这个问题甚至不是承诺特定的,请参阅如何在callback中访问正确的`this`上下文? 对于通用解决scheme:
….then(this.method2.bind(this))… // ES5 .bind() Function method ….then((r) => this.method2(r))… // ES6 arrow function
然而, 蓝鸟提供了另一种方式来调用函数作为一种方法:
this.service.serviceMethod(args) .bind(this) .then(this.method2) .catch(onRejected);
我应该补充说,这是一个通用的JavaScript问题,也可以使用纯JavaScriptfunction来解决。 例如,你也可以这样做:
User.prototype.method1 = function () { ............. this.service.serviceMethod(args) .then(this.method2.bind(this)) .catch(onRejected); };
这使用内置于Javascript中的Function.prototype.bind()
,并显示在每个函数上。 这将创build一个函数存根(即传递给.then()
的函数.then()
并且在调用method2()
之前,存根会自动重新method2()
所需的值。