【发布时间】:2018-12-04 17:35:26
【问题描述】:
我试图了解为什么我的 this 绑定在以下示例中不起作用。 预期的输出是: NEXT, FUNC-01, 1, NEXT, etc.等
相反,我收到一个错误“无法读取未定义的属性 '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();
【问题讨论】:
标签: arrays function ecmascript-6 binding this