DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 簡單實用的js調試logger組件實現代碼
簡單實用的js調試logger組件實現代碼
編輯:關於JavaScript     
但這兩種方式都有它的局限性,alert會有中斷,有些時候alert出來的值並不可靠,閉包的時候用alert可能會得到不正確的值。debugger使用起來其實也挺糾結的,只有ie支持。所以最合理的方式是js把運行過程需要調試的值輸出到頁面,或者寫到cookie也可以,這種方式不會有alert中斷帶來值不正確的問題,也不會受浏覽器類型的限制,唯一糾結的是操作起來很麻煩。
於是,有了下面說的這個js組件。這個組件的實現參考了log4net組件的記錄方式,我們利用這個js的logger組件,就可以用log的輸出的方式來進行你的調試工作了。
復制代碼 代碼如下:
/*
js調試組件
*/
(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);
})();

怎麼使用呢?
這個js組件往window對象注冊了Logger對象,我們可以用Logger.log/Logger.debug/Logger.info/Logger.warn/Logger.error/Logger.fatal來輸出不同的調試信息。
示例代碼如下:
復制代碼 代碼如下:
Logger.debug(new Date());
Logger.debug(new Date().addHours(3));

很簡單,再也不用每個地方都寫document.getElementId().innerHtml或者alert/debugger來輸出內容了。
示例代碼中使用的addHours是我擴展js的Date對象方法,想要了解更多的朋友可以查看《擴展js的Date方法》。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved