这在 ES6 的嵌套箭头函数中没有按预期工作

This not working as expected in nested arrow functions in ES6

我是箭头函数的新手,我不明白为什么我可以使用这段代码:

const adder = {
    sum: 0,
    add(numbers) {
        numbers.forEach(n => {
            this.sum += n;
        });
    }
};

adder.add([1,2,3]);
// adder.sum === 6

... 它工作正常,但在以下情况下 this 未正确绑定:

const adder = {
    sum: 0,
    add: (numbers) => {
        numbers.forEach(n => {
            this.sum += n;
        });
    }
};

adder.add([1,2,3]);
// Cannot read property sum

来自 MDN:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.(...)

意思是在箭头函数内部,this 指的是最外面的 this。如果您 运行 在浏览器中,thiswindow 对象。

使用 adder.sum 而不是 this.sum

Fiddle

箭头函数允许到达词法this。这是定义 adder 的上下文,而不是 adder 本身。

预计会这样工作:

function Foo () {
    // this === foo;
    this.sum = 0;

    const adder = {
        sum: 0,
        add: (numbers) => {
            numbers.forEach(n => {
                // this === foo;
                this.sum += n;
            });
        }
    };

    adder.add([1,2,3]);
}

const foo = new Foo;

const adder = {
    sum: 0,
    add(numbers) { ... }
};

的快捷方式
const adder = {
    sum: 0,
    add: function (numbers) { ... }
};

所以 add 方法在像 adder.add(...).

这样调用时将具有 adder 作为 this