I was just trying to learn and understand jQuery source code (so far with little success X_X) in order to improve my JavaScript skills. As my understand of JavaScript increases I came up with this little logging/debugging tool. As of my level of JavaScript I am posting the code here for people to judge and audit. So potentially I can learn from the comments made. Can someone please point out potential issues, improvements? I tried to encapsulate the console implementation and map it to window.$console (the only place that messes with global scope).
(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;
}());
Usage
$console.init("console").log("hello world");
$console.assert(true, "This is a pass.");
ps: As I've made a few revisions to the code the question is quite different from what it was originally.