首页 > 解决方案 > 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();

标签: arraysfunctionecmascript-6bindingthis

解决方案


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();

推荐阅读