[英]What is the difference between window.console.log and console.log
[英]How to restore / reset window.console.log
我有一個將 window.console.log 更改為函數的應用程序。
我想在某個頁面上將 window.console.log 重置為正常狀態,但是當我運行時delete window.console.log;
並調用 console.log('asd'); 我得到一個例外
TypeError: console.log is not a function. (In 'console.log(error)', 'console.log' is undefined)
我如何正確恢復它以便某個頁面可以正常地簡單地使用 console.log 而不是我擁有的自定義頁面?
如果您能夠在應用程序修改console.log
之前訪問代碼,您可以執行以下操作:
window.defaultConsoleLog = console.log;
// here would be the code where the application modifies console.log
// calling console.log would now be the modified version from the application:
console.log('Hello');
// calling defaultConsoleLog would now call the original console.log:
defaultConsoleLog.log('Hello');
// OR
window.defaultConsoleLog('Hello');
// you can then reset to the original console.log like this:
console.log = window.defaultConsoleLog;
當您執行delete window.console.log
,這會從window.console
對象中刪除該函數而不是重置它。
您可以簡單地將舊的本機函數存儲在其他變量或屬性中,並在以后恢復它。 例如 :
// Storing the native console.log into a property in window window.oldLog = window.console.log // Overriding the console.log function console.log = (str) => { document.getElementById('logs').textContent += str } console.log('Calling the new console.log') window.oldLog('Calling the old console.log') // Now resetting the native console.log console.log = window.oldLog // Clearing up delete window.oldLog console.log('Calling the restored console.log')
<pre id="logs"></pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.