我只是想学习和理解 jQuery 源代码(到目前为止收效甚微 X_X),以提高我的 JavaScript 技能。随着我对 JavaScript 理解的增加,我想出了这个小日志/调试工具。就我的 JavaScript 水平而言,我在这里发布代码供人们判断和审核。因此,我有可能从所发表的评论中学习。有人可以指出潜在的问题,改进吗?我试图封装控制台实现并将其映射到 window.$console (唯一与全局范围混淆的地方)。
(function() {
var proxy = {}, //use private proxy object to prevent binding to global (window) object
_id = "",
_warning = false;
results = {};
if (this.$console) { //check if $console exists in global (window)
warning("$console is conflicting with existing object and could not be mapped.");
}
else {
this.$console = proxy; //if undefined we then map proxy to global (window) object
}
proxy.init = function(id) { //map the display ol html element on the page
_id = id;
results = document.getElementById(id);
return this;
}
proxy.log = function(msg) {
append(msg);
return this;
};
proxy.assert = function(pass, msg) {
var html = (pass) ? "<b style=\"color: green;\">Pass</b>, " + msg
: "<b style=\"color: red;\">Fail</b>, " + msg ;
append(html);
return this;
}
proxy.error = function(msg) {
var html = "<b style=\"color: red;\">Error</b>, " + msg + "";
append(html);
return this;
}
function append(msg) {
if (results != null) {
results.appendChild(getChild("li", msg));
}
else {
warning("Message could not be appended to element with \"Id: " + _id + "\".");
}
return this;
};
function getChild(type, html) {
var child = document.createElement(type);
child.innerHTML = html;
return child;
}
function warning(msg) {
if (!_warning) {
_warning = true;
alert(msg);
}
}
return proxy;
}());
用法
$console.init("console").log("hello world");
$console.assert(true, "This is a pass.");
ps:由于我对代码进行了一些修改,所以问题与最初的问题完全不同。