[JavaScript] 將 console.log 當函式參數使用,出現 Illegal invocation 的錯誤?

[JavaScript] 將 console.log 當函式參數使用,出現 Illegal invocation 的錯誤?

今天用 JavaScript 想把 console.log 當做函式的參數來傳,

再拿來當像 C 的函式指標來使用,結果遇到奇怪的問題…

 

程式如下,我在 jsDebugLog() 函式裡,把 console.log 當作參數傳給 jsDebugLogImpl(),

而在 jsDebugLogImpl() 裡會用這個參數來直接呼叫函式:

function jsDebugLogImpl(func, sLog)
{
if (g_bEnableDebugMode)
{
func(sLog);
}
}
function jsDebugLog(sLog)
{
jsDebugLogImpl(console.log, sLog);
}
function jsWarningLog(sLog)
{
jsDebugLogImpl(console.warn, sLog);
}

 

上面的寫法看起來沒什麼問題,但執行後出現了 TypeError: Illegal invocation 的錯誤訊息…

有點搞不懂發生了什麼事情… 在網路上查了一下,原來是 this 指標的問題:

console.log() 預期 this 會指向 console 物件,

但當我們將 console.log 直接當參數傳給 jsDebugLogImpl() 時,this 變成了全域的 Window 物件…

 

要解決這個問題,可以用 bind() 將 this 指標設定成 console 後產生出新的函式,

再呼叫這個函式,就沒問題了:

// func(sLog);
(func.bind(console))(sLog);

 

另一種寫法是利用 call() 也可以將 console 指定成 this 指標:

func.call(console, sLog);

 

參考資料:

Illegal Invocation error when console.log passed in a function

TypeError: Illegal Invocation on console.log.apply

#Javascript:this用法整理

(本頁面已被瀏覽過 179 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料