Make an Object loggable()

August 23rd, 2010 posted by admin

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