First override toString
for your object or the prototype:
var Foo = function(){};
Foo.prototype.toString = function(){return 'Pity the Foo';};
var foo = new Foo();
Then convert to string to see the string representation of the object:
//using JS implicit type conversion
console.log('' + foo);
If you don't like the extra typing, you can create a function that logs string representations of its arguments to the console:
var puts = function(){
var strings = Array.prototype.map.call(arguments, function(obj){
return '' + obj;
});
console.log.apply(console, strings);
};
Usage:
puts(foo) //logs 'Pity the Foo'
puts(foo, [1,2,3], {a: 2}) //logs 'Pity the Foo 1,2,3 [object Object]'
Update
E2015 provides much nicer syntax for this stuff, but you'll have to use a transpiler like Babel:
// override `toString`
class Foo {
toString(){
return 'Pity the Foo';
}
}
const foo = new Foo();
// utility function for printing objects using their `toString` methods
const puts = (...any) => console.log(...any.map(String));
puts(foo); // logs 'Pity the Foo'