Javascript 使用promise时,`this`对象未定义
在下面的示例中,当我运行此代码并调用start函数时,仅在Javascript 使用promise时,`this`对象未定义,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,在下面的示例中,当我运行此代码并调用start函数时,仅在\u一个函数中定义了此。继续执行下一个功能时,此功能未定义。有什么解释吗?如何解决这个问题? 提前谢谢 'use strict'; class MyClass { constructor(num) { this.num = num; } start() { this._one() .then(this._two) .then(this._three) .then(this
\u一个函数中定义了此。继续执行下一个功能时,此功能未定义。有什么解释吗?如何解决这个问题?
提前谢谢
'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();
将承诺链修改为:
start() {
this._one()
.then(this._two.bind(this))
.then(this._three.bind(this))
.then(this._four.bind(this))
.catch((err) => {
console.log(err.message);
});
}
bind()
将修改处理程序,使其与正确的此
对象(MyClass的实例)绑定。您将在MyClass实例上实现方法调用
在初始场景之后,Promise将调用处理程序(\u two
,\u two
)作为常规函数,在严格模式下
将此
作为未定义的
有关bind()
的更多详细信息,您可以使用箭头函数并调用_two()、_two()等。。。在他们里面。执行此操作时,将自动绑定此文件
this._one()
.then(() => { this._two() })
.then(() => { this._three() })
.then(() => { this._four() })
.catch((err) => {
console.log(err.message);
});
你的这个在\u two
中是未定义的,因为你失去了词汇引用。您正在将一个函数的回调传递给另一个函数(promisethen
)。调用此函数时,将释放this
您可以使用bind为调用的函数设置this
的上下文,然后
:
.then(this.\u two.bind(this))
使用ES6,您还可以使用fat箭头来保留此
:
.then(()=>this.\u two())
我个人使用的是蓝鸟
承诺,而不是本地ES6。
这承诺执行速度更快(),API更方便,在浏览器和node.js()中都可用
我将这个
值绑定到链中的第一个承诺-之后您的示例运行良好
'use strict';
var Promise = require('bluebird');
class MyClass {
constructor(num) {
this.num = num;
}
start() {
Promise.bind(this)
.then(this._one)
.then(this._two)
.then(this._three)
.then(this._four)
.catch((err) => {
console.log(err.message);
});
}
_one() {
console.log('num: ' + (this.num += 1));
return new Promise((resolve, reject) => {
resolve();
});
}
_two() {
console.log('num: ' + (this.num += 2));
return new Promise((resolve, reject) => {
resolve();
});
}
_three() {
console.log('num: ' + (this.num += 3));
return new Promise((resolve, reject) => {
resolve();
});
}
_four() {
console.log('num: ' + (this.num += 4));
return new Promise((resolve, reject) => {
resolve();
});
}
}
let myClass = new MyClass(4);
myClass.start();
我还稍微改变了一些方法,这样你就可以看到在this.num
删除我的反对票方面取得的进展,因为整个答案都被重写了:)@fmsf我认为OP遇到了一些问题,这些问题的承诺都解决了未定义的:)但是问题出在这个
参数中。您要么删除块,要么将return
添加到函数中。