2016-07-26 100 views
0

首先我想这一点 -为什么“this”在胖箭头函数定义中未定义?

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

工作正常。现在我用胖箭头尝试同样的事情。在这种情况下,这个“未来”是未定义的。

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

这给了我一个错误

TypeError: Cannot read property 'name' of undefined

我的教训是,胖箭头语法是更好的方式处理隐含的“本”。请解释为什么会发生这种情况。

+0

是的,这个问题不回答这个问题:http://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions –

+0

HTTPS://developer.mozilla。 org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Dellirium

+0

也是[函数与函数声明/表达式的重复:它们是否等同/可交换?](http://stackoverflow.com/q/34361379/218196 ) –

回答

1

与常规功能一样,Arrow功能没有this或它们自己的,只有自己的常规功能和全球范围以及this

这意味着,只要this将在箭头功能可按被称为,它会开始看时查找范围找到this值,或者在这种情况下,最多也发现,该object是不是有一个this ,因此它达到了全球范围,并将this的价值与全球范围绑定,在那里它找不到任何东西。这两个例子将解决你的疑问。功能

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

var a = 'global!!!'; 

obj.foo(); 

这里内

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

var a = 'global!!!'; 

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

包装箭头,我试图解释this的behvauiour在深入箭头。

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