自己想封裝一個logger類調用console方法的時候能打出時間、模塊名稱等額外的info,而IE console下的方法不支持call、apply調用,也不能直接給console.info等方法設置call方法,很麻煩。。。
可以利用Function.apply、Function.prototype.apply、Object.apply等方法代替:
Function.apply.apply(consloe.info, [console, aArgs]);
or
Function.apply.call(consloe.info, console, aArgs);
注:其中aArgs為數組
function doLog(sMethod , aArgs){
if(navigator.userAgent.toLowerCase().indexOf('msie') > -1){
Function.apply.apply(console[sMethod], [console, aArgs]);
}else{
console[sMethod].apply(console,aArgs);
}
}
var Logger=function(sModule){
this._name=sModule;
};
var methods=['log','debug','info','error','warn'];
for(var i=0,len=methods.length; i<len; i++){
(function(method){
Logger.prototype[method]=function(){
var sDate='['+ new Date().toLocaleString()+']';
var aArgs=Array.prototype.slice.call(arguments,0);
aArgs.unshift(sDate);
aArgs.push('('+ this._name+')');
doLog(method,aArgs);
}})(methods[i]);
}
//-----------------------------
var log=new Logger('chatList');
log.info('hello');
ok,成功輸出 :[2012年3月7日 18:29:23]hello(chatList)
posted on 2013-11-18 13:42
SIMONE 閱讀(882)
評論(0) 編輯 收藏 所屬分類:
JavaScript