为什么“这”是否定义了一个胖箭头功能定义? [英] Why "this" is undefined inside a fat arrow function definition?

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

问题描述

首先我尝试过 -

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

哪个工作正常。现在我尝试了同样的东西,胖箭头。在这种情况下,这个未定义。

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:无法读取未定义的属性name

TypeError: Cannot read property 'name' of undefined

我学到的是,fat arrow语法更好处理隐含的这。请解释为什么会发生这种情况。

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

推荐答案

请参阅此链接

https://stackoverflow.com/documentation/javascript/186/functions/720/arrow-functions#t=201607261204169177425

总而言之,像常规函数一样,Arrow函数没有这个或他们自己的,只有常规的功能和全局范围,而这个是自己的。

To sum it up, like regular functions, Arrow function does not have a this or their own, only regular function and global scope and this of their own.

这意味着每当这个将在箭头函数中引用时,它将开始查找范围来查找这个,或者在这种情况下,在查找时,发现对象没有 code>,因此它已经达到全局范围,并且将这个的值与全局范围绑定,在那里它不会找到任何东西。这两个例子将会解决你的疑问。

Which would mean that whenever this would be referred in arrow funciton, it will start looking up the scope to find the value of this, or in this case, during look up it found, that the object is not having a this of it's own, hence, it went upto global scope, and binded the value of this with global scope, where it wont find anything. These two example 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();

这里,我试图解释这个为深入的箭头。

Here, I have tried to explain the behvauiour 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天全站免登陆