为什么“这个"?在胖箭头函数定义中是否未定义? [英] Why "this" is undefined inside a fat arrow function definition?

查看:16
本文介绍了为什么“这个"?在胖箭头函数定义中是否未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我尝试了这个 -

const profile = {
    name: 'Alex',
    getName: function(){
      return this.name;
    }
};

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

Which works fine. Now I tried the same thing with fat arrow. In that case "this" is coming undefined.

const profile = {
    name: 'Alex',
    getName: () => {
      return this.name;
    }
};

这给了我一个错误

类型错误:无法读取未定义的属性名称"

TypeError: Cannot read property 'name' of undefined

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

What I learned was, fat arrow syntaxes are way better handling implicit "this". Please explain why is this happening.

推荐答案

与常规函数不同,Arrow 函数没有自己的 this,只有常规函数和全局作用域有 this 自己的.

Unlike regular functions, Arrow functions does not have a this of their own, only regular functions and global scope have this of their own.

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

Which would mean that whenever this would be referred in arrow function, it will start looking up the scope to find the value of this, or in this case, during lookup it found, that the object is not having a this of its own, hence, it went up to global scope and bound the value of this with global scope, where it won't find anything. These two examples will solve your doubt.

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

var a = 'global!!!';

obj.foo();              // global!!!

在函数内包装箭头

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

var a = 'global!!!';

obj.foo();

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

Here, I have tried to explain the behaviour of this for arrow in depth.

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

这篇关于为什么“这个"?在胖箭头函数定义中是否未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆