Moe*_*ler 9 javascript node.js
有没有办法影响console.log提供自定义对象?我试图覆盖但不起作用的customObject.prototype.toString方法.
有任何想法吗?
Joh*_*yHK 18
在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);
Run Code Online (Sandbox Code Playgroud)
输出:
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);
Run Code Online (Sandbox Code Playgroud)
小智 12
先前的答案已在较新版本的节点中弃用。现在需要实现的方法是符号[util.inspect.custom]。
例如:
const util = require('util');
class Custom {
constructor(foo, bar) {
this.foo = foo;
this.bar = bar;
}
[util.inspect.custom](depth, opts) {
return this.foo + this.bar;
}
}
console.log(new Custom(3, 5)); // Prints '8'
Run Code Online (Sandbox Code Playgroud)
最近 (18) Node.js 版本包含此文档片段作为如何跨 Node 和浏览器执行此操作的示例:
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
class Password {
constructor(value) {
this.value = value;
}
toString() {
return 'xxxxxxxx';
}
[customInspectSymbol](depth, inspectOptions, inspect) {
return `Password <${this.toString()}>`;
}
}
const password = new Password('r0sebud');
console.log(password);
// Prints Password <xxxxxxxx>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1842 次 |
| 最近记录: |