[英]How to call another function within the same object?
let role = {
test: (variable) => {
// How do I call toLog(variable) from here?
},
toLog: (variable) => {
console.log(variable);
}
};
我想在 test() function 中調用 toLog() function 但我不知道如何調用。
標准JS函數使用動態綁定, this
取決於誰在運行時調用該方法,因此,如果我們使用role.test()
調用,它將this
綁定到role
。
箭頭函數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
由於您使用的是箭頭函數,因此在此處使用它不起作用,但您將 object 引用為role
,因此您可以將 function 作為role.toLog
從另一個 function 中調用,即test
如下所示
let role = { test: (variable) => { // How do I call toLog(variable) from here? role.toLog(`${variable} from test`); }, toLog: (variable) => { console.log(variable); } }; role.test('hello world');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.