除錯這件事,永遠卡在最麻煩的那個環境上。比如 IE6,開發者工具幾乎等於零,一行 console.log 就能讓整個腳本掛掉;就算換到現代瀏覽器,為了確認某段業務邏輯到底有沒有跑到,反覆下斷點、單步執行,往往比直接印一行訊息慢得多。
所以「即時日誌輸出」是個很划算的投資:程式跑到哪、變數是什麼、條件有沒有成立,一眼就看得到。下面這支小工具就是為這個場景寫的,它會在頁面左下角建立一個可折疊的控制台,把除錯訊息按行號列出來,並支援簡單的斷言。
(function(){
var cache = [];
var el = null;
this.__debugLine = 1;
function parseObjToStr(obj){
if(obj.constructor == String){
return obj.toString();
}
var ret = [];
for(var o in obj){
if(typeof obj[o] != "function")
ret.push(o + ":" + obj[o]);
}
return ret.join(",");
}
this.assert = function(flag, msg){
msg = {"number":1,"string":1,"boolean":1,"function":1,"undefined":1}[typeof msg]
? msg : parseObjToStr(msg);
// Log.getInstance().debug(msg);
return;
var bgColor = this.__debugLine % 2 == 0
? "background-color:#F8F8F8" : "background-color:#ffffff";
msg = flag == "debug"
? String.format('<div style="{0}"><table style="font-size:12px;border-collapse:collapse !important;"><tbody><tr><td style="height:25px;line-height:25px;border-right:3px solid #6CE26C;width:45px; text-align:center;"><code style="font-weight:bold;color:gray">{1}</code></td><td><b style="color:{2};margin-left:5px;">[{3}]:</b>{4}</td></tr></tbody></table></div>',
bgColor, this.__debugLine, "#333333", flag, msg)
: msg;
if(flag.constructor != String)
msg = String.format('<div style="{0}"><table style="font-size:12px;border-collapse:collapse !important;line-height:25px;"><tbody><tr><td style="height:25px;line-height:25px;border-right:3px solid #6CE26C;width:45px;text-align:center;"<code style="font-weight:bold;color:gray">{1}</code></td><td><b style="color:{2};margin-left:5px;">[{3}]:</b>{4}</td></tr></tbody></table></div>',
bgColor, this.__debugLine, flag ? "green" : "red",
flag ? "PASS " : "FAIL ", msg);
this.__debugLine++;
if(cache != null){ cache[cache.length] = msg; }
else{ el.innerHTML += msg; }
}
function applyStyle(el, style){
for(var pro in style){ el.style[pro] = style[pro]; }
}
addEvent(window, "load", function(){
return;
el = document.createElement("div");
var elStyle = {backgroundColor:"#ffffff", color:"#333333",
border:"1px solid #dcdada", borderLeft:"0px solid #6CE26C",
borderRight:"0px solid #6CE26C", lineHeight:"25px",
textAlign:"left", listStyleType:"none", margin:"0px",
maxHeight:"200px", overflow:"auto"};
var head = document.createElement("div");
var headStyle = {backgroundColor:"#fef5c5", lineHeight:"25px"};
head.innerHTML = "<span style='float:left;font-weight:bold;margin-left:10px;font-size:13px;'>調試信息控制台</span><span id='console_andler' style='float:right;margin-right:20px;cursor:pointer' title='展開/折疊'>+</span><br style='clear:both'>";
var wrap = document.createElement("div");
var wrapStyle = {overflow:"hidden", backgroundColor:"#ffffff", color:"#333333",
border:"1px solid #C0C0C0", "fontSize":"12px", "margin":"5px",
position:"fixed", left:"0px", bottom:"0px", width:"97%"};
var foot = document.createElement("div");
var footStyle = {padding:"0", textAlign:"left"};
foot.innerHTML = ">>><input type='text' value='' id='console_eval' style='margin:0;width:90%;border:none;line-height:25px;height:25px;text-indent:10px;'/>";
applyStyle(wrap, wrapStyle);
applyStyle(head, headStyle);
applyStyle(el, elStyle);
applyStyle(foot, footStyle);
wrap.appendChild(head);
wrap.appendChild(el);
wrap.appendChild(foot);
document.body.appendChild(wrap);
el.innerHTML = cache.join("");
cache = null;
function toggle(){
if(!this.hide){
el.style.display = "none";
foot.style.display = "none";
wrap.style.width = "200px";
this.hide = true;
} else {
el.style.display = "";
foot.style.display = "";
wrap.style.width = "98%";
this.hide = false;
}
}
head.onclick = function(){ toggle.call(this); };
head.onclick();
document.getElementById("console_eval").onkeydown = function(e){
e = e || window.event;
if(e.keyCode == 13){
try{
eval.call(window, String.format("assert('debug',{0})", this.value));
} catch(e){
assert("debug", e.message);
}
el.scrollTop = el.scrollHeight;
}
}
});
})();
呼叫方式刻意做得跟一般除錯函式一樣直覺:
assert("debug", "調試信息");
執行後,頁面上就會出現對應的日誌列。除了單純的訊息,它也支援斷言式寫法:傳入一個真假值當第一個參數,通過顯示綠色 PASS,沒通過就顯示紅色 FAIL,跑完一批檢查再回頭看畫面,哪裡壞掉一目了然。
window.onload 之前呼叫的訊息會先塞進 cache 陣列,等控制台建好之後再一次寫入,不會因為 DOM 還沒就緒而丟掉訊息。parseObjToStr 會把傳入的物件攤平成 key:value 串,省下每次手動拼字串的麻煩。assert('debug', ...) 執行,等於一個簡陋的 REPL。需要補一句:這裡的日誌輸出樣式靈感來自 jQuery 作者當年的一段單元測試模組。另外程式碼中 assert 與 load 回呼裡都留了 return;,那是作者刻意關掉渲染的開關,實際使用時記得移除,否則什麼都不會顯示。