ES6 Массив функций, проблемы с этим - PullRequest
0 голосов
/ 04 декабря 2018

Я пытаюсь понять, почему моя привязка не работает в следующем примере.Ожидаемый результат: NEXT, FUNC-01, 1, NEXT и т. Д. И т. Д.

Вместо этого я получаю сообщение об ошибке «не могу прочитать свойство« counter »из undefined», что означает «теряю эту привязку.Я не понимаю, как сохранить эту привязку.Вот код:

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

1 Ответ

0 голосов
/ 04 декабря 2018

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