2016-09-22 61 views
3

我有2箱子可见性的“本”中箭功能

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在这种情况下箭头功能范围无法使用。

+2

胖箭头函数中的作用域不会调用它所调用的对象的上下文 –

回答

3

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

箭头函数从创建函数的范围中导入this的值。

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