util.inspect.custom
- <symbol> 可用于声明自定义的检查函数。
除了可以通过 util.inspect.custom
访问之外,此符号是全局地注册,可以在任何环境中作为 Symbol.for('nodejs.util.inspect.custom')
访问。
使用此允许以可移植方式编写代码,以便在 Node.js 环境中使用自定义检查功能并在浏览器中忽略。
util.inspect()
函数本身作为第三个参数传给自定义检查函数以允许进一步的可移植性。
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);
// 打印 Password <xxxxxxxx>
有关更多详细信息,请参阅对象上的自定义检查函数。
- <symbol> that can be used to declare custom inspect functions.
In addition to being accessible through util.inspect.custom
, this
symbol is registered globally and can be
accessed in any environment as Symbol.for('nodejs.util.inspect.custom')
.
Using this allows code to be written in a portable fashion, so that the custom
inspect function is used in an Node.js environment and ignored in the browser.
The util.inspect()
function itself is passed as third argument to the custom
inspect function to allow further portability.
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>
See Custom inspection functions on Objects for more details.