Sar*_*aro 2 javascript node.js ecmascript-6
在下面的示例中,当我运行此代码时,调用start函数,只定义了内部_one函数this.继续下一个功能时_two,this未定义.任何解释?以及如何解决这个问题?提前致谢.
'use strict';
class MyClass {
constructor(num) {
this.num = num;
}
start() {
this._one()
.then(this._two)
.then(this._three)
.then(this._four)
.catch((err) => {
console.log(err.message);
});
}
_one() {
console.log('num: ' + this.num);
return new Promise((resolve, reject) => {
resolve();
});
}
_two() {
console.log('num: ' + this.num);
return new Promise((resolve, reject) => {
resolve();
});
}
_three() {
console.log('num: ' + this.num);
return new Promise((resolve, reject) => {
resolve();
});
}
_four() {
console.log('num: ' + this.num);
return new Promise((resolve, reject) => {
resolve();
});
}
}
let myClass = new MyClass(4);
myClass.start();
Run Code Online (Sandbox Code Playgroud)
将promises链修改为:
start() {
this._one()
.then(this._two.bind(this))
.then(this._three.bind(this))
.then(this._four.bind(this))
.catch((err) => {
console.log(err.message);
});
}
Run Code Online (Sandbox Code Playgroud)
在bind()将修改处理程序以正确的绑定this对象(实例MyClass).您将在MyClass实例上实现方法调用.
在您的初始场景之后,Promise将调用处理程序(_two,_three)作为常规函数,其Strict mode将具有thisas undefined.
在这里看到更多细节bind().