2016-12-25 92 views
10
let role = { 
    test: (variable) => { 
     // How do I call toLog(variable) from here? 
    }, 
    toLog: (variable) => { 
     console.log(variable); 
    } 
}; 

我想調用test()函數內的toLog()函數,但我不知道如何去做。如何在同一個對象中調用另一個函數?

+3

'role.toLog()'或使用一個類,所以你可以簡單地使用'this.toLog()' – Ties

+2

[在這裏你不需要他們不要使用箭頭功能!](http://stackoverflow.com/q/34361379/1048572)通過方法語法(在對象字面量中),您可以照常調用'this.toLog'。 – Bergi

回答

11

標準JS函數使用動態綁定,this取決於誰在呼叫上運行的方法,因此,如果我們把它用role.test(),它將綁定thisrole

箭頭函數將this綁定到當前上下文中。例如,如果代碼在瀏覽器的控制檯中被寫入,則this被綁定到window對象。這就是所謂的靜態詞彙結合,這意味着綁定this它在定義關閉

如果你不會使用箭頭功能,this將指向對象本身時role叫:

const role = { 
 
    test(variable){ 
 
     this.toLog(variable); 
 
    }, 
 
    toLog(variable) { 
 
     console.log(variable); 
 
    } 
 
}; 
 

 
role.test(5);

在這種情況下,我們不希望綁定this到外的上下文,所以我們跳過靜態支持動態的結合之一。

但是,如果我們將此方法用作回調,則根據誰在運行方法,動態綁定將更改this。爲了防止這種情況,我們必須使用bind創建一個明確的靜態綁定到role

const role = { 
 
    test(variable) { 
 
     this.toLog(variable); 
 
    }, 
 
    toLog(variable) { 
 
     console.log(variable); 
 
    } 
 
}; 
 

 
let test = role.test; 
 

 
try { 
 
    test(20); // will throw an error - this.toLog is not a function - because this points to window 
 
} catch (e) { 
 
    console.log(e); 
 
} 
 

 
test = role.test.bind(role); 
 

 
test(25); // will work because it's staticly binded to role

相關問題