调整自定义对象的console.log行为

有什么办法来影响什么console.log发出自定义对象? 我试图覆盖customObject.prototype.toString方法,虽然没有工作。

有任何想法吗?

在node.js中, console.log在每个参数console.log调用util.inspect而不使用格式化占位符。 所以如果你在你的对象上定义了一个inspect(depth, opts)方法,它将被调用来获得你自定义的对象的string表示。

例如:

 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); 

输出:

foo = BAR

或者使用一个类:

 class Custom { constructor(foo) { this.foo = foo; } inspect(depth, opts) { return 'foo = ' + this.foo.toUpperCase(); } } var custom = new Custom('bar'); console.log(custom);