Make an Object loggable()
loggable() is a simple little function for safely making a JavaScript object (console) loggable. (Name was inspired by @furf‘s jquery.bindable.js.)
/**
* Loggable adds a log method to the passed object.
* @param obj {Object} Object which will get a new log() method
* @param objName {String} Optional parameter for displaying a string before each log output
* @param debugMode {boolean} Optional switch for disabling logging
*/
function loggable(obj /* , objName, debugMode */){
var objName = arguments[1] || "",
debugMode = (typeof arguments[2]!=="undefined") ? arguments[2] : true,
prefix = objName ? objName + ": " : "";
obj.log = (function(prefix){
return function(){
if (debugMode && typeof console!=="undefined"){
if (arguments.length){
arguments[0] = prefix + arguments[0];
}
console.log.apply(null, arguments);
}
}
})(prefix);
return obj;
};
So if you have an object like:
var obj = {
name : "Alex",
getName : function(){ return "Alex" },
setName : function(name){
obj.name = name;
obj.log("name was set to", name);
}
}
loggable(obj, "Obj");
Then, executing:
obj.setName("Balthazar");
Will log this in your console (Firebug or otherwise):
Obj: name was set to Balthazar.
Here it is on GitHub: http://gist.github.com/547926




Subchild is a blog about web development. It's author is Aleksandar Kolundzija, himself a web developer
for 10++ years, presently a Hacker-in-Residence at betaworks. Prior to betaworks, Alex worked at Google, Meebo,
MLB Advanced Media (MLB.com), Razorfish, and elsewhere.