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').
使用这个可以以可移植的方式编写代码,这样自定义的 inspect 函数在 Node.js 环境中会被使用,而在浏览器中则会被忽略。util.inspect() 函数本身作为第三个参数传递给自定义 inspect 函数,以便进一步提高可移植性。
🌐 Using this allows code to be written in a portable fashion, so that the custom
inspect function is used in a 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.