为什么在胖箭头函数定义中未定义"this"?

use*_*043 8 javascript ecmascript-6

首先我尝试了这个 -

const profile = {
    name: 'Alex',
    getName: function(){
      return this.name;
    }
};
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.现在我用胖箭尝试了同样的事情.在那种情况下,"这个"未定义.

const profile = {
    name: 'Alex',
    getName: () => {
      return this.name;
    }
};
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误

TypeError:无法读取未定义的属性"name"

我学到的是,胖箭头语法更好地处理隐含的"this".请解释为什么会发生这种情况.

Ani*_*odi 9

像常规函数一样,Arrow函数没有this自己的,也没有自己的常规函数​​和全局范围this.

这意味着每当this在箭头函数中引用它时,它将开始查找范围以找到它的值this,或者在这种情况下,在它找到的查找期间,它object没有this自己的值,因此,它上升了到全局范围并绑定全局范围的值this,它将找不到任何东西.这两个例子将解决您的疑问.

var obj = {
    a : 'object???',
    foo : () => { console.log(this.a) }
};

var a = 'global!!!';

obj.foo();              // global!!!
Run Code Online (Sandbox Code Playgroud)

在函数中包装箭头

var obj = {
    a : 'object???',
    foo : function() {
        return (() => {
            console.log(this.a)
        })();
    }
};

var a = 'global!!!';

obj.foo();
Run Code Online (Sandbox Code Playgroud)

在这里,我试图this深入解释箭头的行为.

https://github.com/anirudh-modi/JS-essentials/blob/master/ES2015/Functions/Arrow%20functions.md#how-this-is-different-for-arrow-functions

  • `obj.foo();` 将打印 `undefined`,而不是 `global!!!`。 (3认同)