欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

簡(jiǎn)單實(shí)用的js調(diào)試logger組件實(shí)現(xiàn)代碼

 更新時(shí)間:2010年11月20日 20:27:05   作者:  
開(kāi)發(fā)js組件的時(shí)間調(diào)試總是麻煩的,最常用的就是用alert或者debugger來(lái)測(cè)試js的運(yùn)行狀態(tài)。
但這兩種方式都有它的局限性,alert會(huì)有中斷,有些時(shí)候alert出來(lái)的值并不可靠,閉包的時(shí)候用alert可能會(huì)得到不正確的值。debugger使用起來(lái)其實(shí)也挺糾結(jié)的,只有ie支持。所以最合理的方式是js把運(yùn)行過(guò)程需要調(diào)試的值輸出到頁(yè)面,或者寫(xiě)到cookie也可以,這種方式不會(huì)有alert中斷帶來(lái)值不正確的問(wèn)題,也不會(huì)受瀏覽器類(lèi)型的限制,唯一糾結(jié)的是操作起來(lái)很麻煩。
于是,有了下面說(shuō)的這個(gè)js組件。這個(gè)組件的實(shí)現(xiàn)參考了log4net組件的記錄方式,我們利用這個(gè)js的logger組件,就可以用log的輸出的方式來(lái)進(jìn)行你的調(diào)試工作了。
復(fù)制代碼 代碼如下:

/*
js調(diào)試組件
*/
(function () {
var logger = function (level, object, viewType) {
this.level = level;
this.object = object;
this.viewType = viewType;
}
logger.LEVEL_DEBUG = 0;
logger.LEVEL_INFO = 1;
logger.LEVEL_WARN = 2;
logger.LEVEL_ERROR = 3;
logger.LEVEL_FATAL = 4;
logger.VIEW_TYPE_ALERT = 0;
logger.VIEW_TYPE_APPEND = 1;
logger.prototype = {
setLevel: function (level) {
this.level = level;
},
setObject: function (o) {
if (typeof o == 'string') {
this.object = document.getElementById(o);
} else {
this.object = o;
}
},
setViewType: function (type) {
this.viewType = type;
},
log: function (s) {
this.message(100, s);
},
debug: function (s) {
this.message(logger.LEVEL_DEBUG, s);
},
info: function (s) {
this.message(logger.LEVEL_INFO, s);
},
warn: function (s) {
this.message(logger.LEVEL_WARN, s);
},
error: function (s) {
this.message(logger.LEVEL_ERROR, s);
},
fatal: function (s) {
this.message(logger.LEVEL_FATAL, s);
},
message: function (level, s) {
if (level >= this.level) {
if (this.object != null) {
this.object.innerHTML = s;
} else if (this.viewType == logger.VIEW_TYPE_ALERT) {
alert(s);
} else {
document.body.appendChild(document.createTextNode(s));
document.body.appendChild(document.createElement("br"));
}
}
}
};
if (typeof window.Logger == 'undefined' || window.Logger == null)
window.Logger = new logger(logger.LEVEL_DEBUG, null, logger.VIEW_TYPE_APPEND);
})();

怎么使用呢?
這個(gè)js組件往window對(duì)象注冊(cè)了Logger對(duì)象,我們可以用Logger.log/Logger.debug/Logger.info/Logger.warn/Logger.error/Logger.fatal來(lái)輸出不同的調(diào)試信息。
示例代碼如下:
復(fù)制代碼 代碼如下:

Logger.debug(new Date());
Logger.debug(new Date().addHours(3));

很簡(jiǎn)單,再也不用每個(gè)地方都寫(xiě)document.getElementId().innerHtml或者alert/debugger來(lái)輸出內(nèi)容了。
示例代碼中使用的addHours是我擴(kuò)展js的Date對(duì)象方法,想要了解更多的朋友可以查看《擴(kuò)展js的Date方法》。

相關(guān)文章

最新評(píng)論