2016-09-22 39 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的值將取決於對象文字周圍的內容,但肯定不會是對象本身。