我正在學習更多關於JavaScript OOP的知識,通過滾動我自己的console.log變體並添加一些我想要的功能。JavaScript對象中的任意方法名稱
到目前爲止,我有
debug = {
consoleAvailable : (typeof console == "object"),
reportToConsole : 0,
list : [],
setReporting : function(level){
this.reportToConsole = level;
return true;
},
log : function(){
if (this.reportToConsole>0 && this.consoleAvailable && typeof console.log=="function") console.log.apply(console, this.log.arguments);
this.list.push({'type':'log', 'msg':this.log.arguments});
return true;
},
};
這是所有工作很好,但我不希望有列出所有的日誌,錯誤,警告等功能。相反,我希望能夠只輸入debug。[something]和一個函數來解釋[something]並以與我有日誌函數工作相同的方式執行它。
這甚至可能嗎?如果是這樣,我該怎麼辦呢?
以下是我希望能夠做的一些例子。
debug.setReporting(1); //yes, I want to print to console
debug.log('foo', 'bar', 'baz'); //arbitrary number of arguments (this is already working)
debug.error('qux'); //function I haven't named, but there is a console.error function
debug.arbitraryName([1, 2, 3]); //no function for console.arbitraryName (ideally it would just console.log the argument(s)
編輯
好了,它看起來像@Rob W公司的方法是要走的路,但我有麻煩實施。似乎我沒有正確或類似地傳遞函數的名稱。我這裏有一個小提琴顯示問題http://jsfiddle.net/xiphiaz/mxF4m/
結論
它看起來像有太多的瀏覽器怪癖獲得無需編寫瀏覽器特定的代碼真正通用的調試器,所以不是我剛纔列舉我最常用的日誌功能(日誌,警告和錯誤)。這讓我可以選擇進一步自定義這些功能的結果。
結果:
debug = {
consoleAvailable : (typeof console == "object"),
reportToConsole : 0,
list : [],
setReporting : function(level){
this.reportToConsole = level;
return true;
},
log : function(){
if (this.reportToConsole>0 && this.consoleAvailable && typeof console.log=="function") console.log.apply(console, this.log.arguments);
this.list.push({type:'log', msg:this.log.arguments});
return true;
},
warn : function(){
if (this.reportToConsole>0 && this.consoleAvailable && typeof console.warn=="function") console.warn.apply(console, this.warn.arguments);
this.list.push({type:'warn', msg:this.warn.arguments});
return true;
},
error : function(){
if (this.reportToConsole>0 && this.consoleAvailable && typeof console.error=="function") console.error.apply(console, this.error.arguments);
this.list.push({type:'error', msg:this.error.arguments});
return true;
}
};
debug.setReporting(1);
debug.log('foo', 'bar', 'baz');
debug.error('qux');
debug.warn({test:"warning"});
console.log(debug.list);
請注意,在IE中,console.log等東西不是函數,因此沒有'apply'方法來傳遞可變數量的參數。你必須對不同長度的單獨調用進行硬編碼:'a = arguments; if(a.length == 1){console.log(a [0])} if(arguments.length == 2){console.log(a [0],a [1]}' – hugomg 2012-03-14 22:26:26
但是我在做在嘗試「apply」之前檢查它是否是函數,這是不夠的嗎? – 2012-03-14 22:28:00
啊,沒關係然後 – hugomg 2012-03-14 22:35:09