arrays - ES6 函数数组,这个有问题
问题描述
我试图理解为什么我的这个绑定在下面的例子中不起作用。预期输出为:NEXT、FUNC-01、1、NEXT 等。
相反,我收到一个错误“无法读取未定义的属性 'counter'”,这意味着我正在丢失 this 绑定。我不明白如何保留该绑定。这是代码:
class NotWorkingThing {
constructor () {
this.nextArray = [
this.func01,
this.func02,
this.func03
];
this.counter = 0;
}
next () {
console.log("NEXT");
const nextFunction = this.nextArray.shift();
nextFunction().bind(this);
};
func01 () {
console.log("FUNC-01");
this.counter ++;
console.log(this.counter);
this.next();
};
func02 () {
console.log("FUNC-02");
this.counter ++;
console.log(this.counter);
this.next();
};
func03 () {
console.log("FUNC-03");
this.counter ++;
console.log(this.counter);
this.next();
};
}
const thing = new NotWorkingThing();
thing.next();
解决方案
Bind 是一个函数的方法,它返回一个可以在之后调用的函数。正确的代码是
class NotWorkingThing {
constructor() {
this.nextArray = [
this.func01,
this.func02,
this.func03
];
this.counter = 0;
}
next() {
console.log("NEXT");
const nextFunction = this.nextArray.shift();
if (!nextFunction) return;
const nextFunctionWithBind = nextFunction.bind(this);
nextFunctionWithBind();
};
func01() {
console.log("FUNC-01");
this.counter++;
console.log(this.counter);
this.next();
};
func02() {
console.log("FUNC-02");
this.counter++;
console.log(this.counter);
this.next();
};
func03() {
console.log("FUNC-03");
this.counter++;
console.log(this.counter);
this.next();
};
}
const thing = new NotWorkingThing();
thing.next();
推荐阅读
- java - 如何使用 Selenium 和 Java 从 Bootstrap Glyphicon 日期选择器中选择日期
- javascript - webworkers 中的 tensorflow.js
- c# - 是否有可能 Nlog 不写相同的消息
- angular - Angular:ng build --prod 上的“对象”类型上不存在属性“数据”
- html5-fullscreen - 在页面加载时进入全屏,无需人工干预
- python - 贷款支付建模 - 计算内部收益率
- php - 如何使用 phpexcel 库在 excel 中嵌入(插入对象)文档?
- angular - MockClientService 没有提供者
- image - 图像与内核的卷积给出白色输出
- java - 未来与可完成的未来?对于这个用例 Completablefuture 会有什么不同吗?