util.inspect.custom
- 类型:<symbol>,可用于声明自定义检查函数。
除了可以通过 util.inspect.custom 访问之外,这个符号是 在全球注册,并且可以在任何环境中通过 Symbol.for('nodejs.util.inspect.custom') 访问。
【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').】
使用这一方法可以使代码以可移植的方式编写,从而在 Node.js 环境中使用自定义的 inspect 函数,而在浏览器中则被忽略。util.inspect() 函数本身作为第三个参数传递给自定义 inspect 函数,以便实现更高的可移植性。
【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.】