2013-08-25 80 views
6

我對此有點困惑。 請找到如下代碼。在函數中傳遞console.log時出現非法調用錯誤

var o={ 
printToConsole: function(f){ 
    f(1); 
} 
}; 

o.printToConsole(console.log); 

//TypeError: Illegal invocation //我得到一個類型錯誤

從執行console.log的定義,我們得到這個

`function log() { [native code] }` 

在Chrome中,清楚地顯示,它不帶任何參數,儘管當我們嘗試在控制檯上打印東西時,我們確實是這樣寫的,即將參數傳遞給console.log。

console.log('Take me on Console'); 

爲什麼我得到這個TypeError以及這個console.log在chrome中的行爲如何?

回答

12

變化

o.printToConsole(console.log); 

o.printToConsole(console.log.bind(console)); 

o.printToConsole(function(){ console.log.apply(console.log, arguments) }); 

當接收機(this)是控制檯的console.log功能只適用(事實上,它是依賴於瀏覽器) 。

+0

你說得對。這取決於瀏覽器。 – Mozak

+0

Firefox在控制檯中顯示消息,而不與控制檯綁定。 – Mozak

+1

找到一個類似的問題http://stackoverflow.com/questions/8904782/uncaught-typeerror-illegal-invocation-in-javascript – Mozak

相關問題