Monday, February 18th, 2008
Self Printing JavaScript Literals
Are you ever sick of seeing Object get printed out when you try to output a variable to your console.
Oliver Steele talks about Self Printing JavaScript Literals where you can clean that up with a toString:
-
-
function makeLiteral(name) {return {toString:function(){return name}}}
-
var L1 = makeLiteral("L1");
-
var L2 = makeLiteral("L2");
-
L1
-
//>>> L1
-
L2
-
//>>> L2
-
Kangax takes it further to support nesting:
-
-
function defineLiteral() {
-
var o = window, args = arguments, prop;
-
for (var i=0, l = arguments.length; i
-
prop = arguments[i];
-
o[prop] = o[prop] || { }; o = o[prop];
-
if (i == l-1) o[‘toString’] = function() {
-
return Array.prototype.join.call(args, ’.’)
-
}
-
}
-
return o;
-
}
-
-
defineLiteral(‘bar’, ‘baz’, ‘qux’, ‘quux’); // => bar.baz.qux.quux
-
bar.baz.qux.quux.toString(); // => ‘bar.baz.qux.quux’
-












“Are you ever sick of seeing Object get printed out when you try to output a variable to your console.”
I can’t say that I have. And I can’t even justify all this work just for the sake of debugging.
I think in FF you can use whatever.source to prettyprint anything.
I must say I agree with Urandom.
Functional JavaScript seems like a python language on shell.
Alternately, you could implement Python’s polymorphic |repr| or Ruby’s |inspect|. Firebug has good object inspection if you log non-strings (with a browsable object inspector, but I don’t believe it’s overridable. I disagree with Urandom and Lon42; inspection is very valuable for debugging and totally worth the bother to copytheft.
@Kris
I don’t think that they’re saying that inspection isn’t valuable for debugging, I think that it is indispensable, but this particular technique doesn’t really gain you much of anything since modern debuggers (like Firebug) have that feature baked in. There are debuggers for IE and other browsers that provide similar abilities. If you *really* need this ability and don’t have a debugger installed, a property dump of the object would be more useful than just a name.