posts - 495,comments - 227,trackbacks - 0

自己想封装一个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 阅读(847) 评论(0)  编辑  收藏 所属分类: JavaScript

只有注册用户登录后才能发表评论。


网站导航: