【问题标题】:Visibility of "this" in Arrow Functions [duplicate]箭头函数中“this”的可见性[重复]
【发布时间】:2016-09-22 13:15:54
【问题描述】:

我有两个案例

const test = {
    foo: function (){
        this.bar();
    },
    bar: function (){
        console.log('bar');
    }
}
test.foo();

在这种情况下,一切正常。

const test = {
    foo: () => {
        this.bar();
    },
    bar: () => {
        console.log('bar');
    }
}
test.foo();

在第二种情况下我得到错误:

Uncaught TypeError: Cannot read property 'bar' of undefined

我知道我可以在foo 函数中写test.bar(),但我很感兴趣为什么在这种情况下this 在箭头函数范围内不可用。

【问题讨论】:

  • 粗箭头函数中的作用域不获取被调用对象的上下文

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

通常,函数中this 的值取决于该函数的调用方式。

箭头函数从创建函数的作用域导入this 的值。

在对象字面量的中间,this 的值将取决于对象字面量周围的内容,但肯定不会是对象本身。

【讨论】: