2011-10-29 58 views
50

console.log獲取未指定數量的參數並將其內容轉儲到一行中。通過代理函數將參數傳遞給console.log作爲第一類參數

有沒有一種方法可以編寫一個函數,將傳遞給它的參數直接傳遞給console.log以維持該行爲?例如:

function log(){ 
    if(console){ 
     /* code here */ 
    } 
} 

這不會是一樣:

function log(){ 
    if(console){ 
     console.log(arguments); 
    } 
} 

由於arguments是一個數組,console.log將轉儲該數組的內容。它也不會是相同的:

function log(){ 
    if(console){ 
     for(i=0;i<arguments.length;console.log(arguments[i]),i++); 
    } 
} 

因爲這將打印所有不同的行。重點是保持console.log的行爲,但通過代理功能log

+ ---

我一直在尋找一個解決方案,我可以適用於未來的所有功能(創建保持的參數完整的處理功能的代理)。如果不能完成,我會接受console.log的具體答案。

回答

77

這應該做到這一點..

function log() { 
    if(typeof(console) !== 'undefined') { 
     console.log.apply(console, arguments); 
    } 
} 

剛(使用spread運營商和rest參數- 雖然arguments可以與傳播直接使用)加入另一種選擇

function log(...args) { 
    if(typeof(console) !== 'undefined') { 
     console.log(...args); 
    } 
} 
+3

這在Chrome/Safari中不起作用。它會拋出「非法調用」錯誤。 – aditya

+3

@aditya,更新後的代碼..我沒有使用正確的上下文..你需要通過'console'作爲'this'參數來應用.. –

+0

太棒了。這工作。謝謝! – aditya

3

是的。

console.log.apply(null,arguments); 

雖然通過arguments對象,並從它創建一個規則排列,但除此之外,這是你如何做到這一點,你可能需要循環。

+1

這不會在Chrome/Safari上。它適用於Firebug,但在這裏尋找一個跨瀏覽器的解決方案。 – aditya

+0

'args = []; for(i = 0; i

+0

沒有。顯然,對'console.log.apply'的任何調用都會引發非法調用錯誤。 – aditya

8

有一個很好的例子,從html5boilerplate代碼包裝console.log以類似的方式確保您不會中斷任何不識別它的瀏覽器。它還添加了歷史記錄並平滑了console.log實現中的任何差異。

它由Paul Irish開發,他寫了一篇文章here

我已經粘貼了以下相關的代碼,這裏是對文件的鏈接項目:https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js

// usage: log('inside coolFunc', this, arguments); 
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ 
window.log = function(){ 
    log.history = log.history || []; // store logs to an array for reference 
    log.history.push(arguments); 
    if(this.console) { 
    arguments.callee = arguments.callee.caller; 
    var newarr = [].slice.call(arguments); 
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr)); 
    } 
}; 

// make it safe to use console.log always 
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}}((function(){try {console.log();return window.console;}catch(err){return window.console={};}})()); 
相關問題