有什么方法可以影响 console.log 发出自定义对象的内容吗? 我试图覆盖 customObject.prototype.toString 方法,但它不起作用。
有什么想法吗?
最佳答案
在 node.js 中,console.log
电话 util.inspect
在没有格式化占位符的每个参数上。因此,如果您在对象上定义 inspect(depth, opts)
方法,它将被调用以获取对象的自定义字符串表示。
例如:
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);
关于javascript - 调整自定义对象的 console.log 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397861/