In node.js, console.log
calls util.inspect
on each argument without a formatting placeholder. So if you define an inspect(depth, opts)
method on your object it will be called to get your custom string representation of the object.
For example:
function Custom(foo) {
this.foo = foo;
}
Custom.prototype.inspect = function(depth, opts) {
return 'foo = ' + this.foo.toUpperCase();
};
var custom = new Custom('bar');
console.log(custom);
Outputs:
foo = BAR
Or using a class:
class Custom {
constructor(foo) {
this.foo = foo;
}
inspect(depth, opts) {
return 'foo = ' + this.foo.toUpperCase();
}
}
var custom = new Custom('bar');
console.log(custom);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…