【问题标题】:ES6 Array of functions, trouble with thisES6 函数数组,这个有问题
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 我对此感到非常困惑。谢谢你。是否可以在类体内使用箭头函数来做同样的事情(假设 babel 配置正确),因为它们没有“this”绑定?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2014-06-29
    • 2011-02-13
    • 2011-04-24
    • 2011-08-26
    相关资源
    最近更新 更多