在下面的示例中,我试图了解为什么我的此绑定不起作用。 预期的输出是: NEXT,FUNC-01、1,NEXT等,等等。
相反,我收到一条错误消息“无法读取未定义的属性'counter'”,这意味着我丢失了此绑定。我不明白如何保持这种约束力。这是代码:
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();
答案 0 :(得分:0)
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();