对象的自定义检查函数
\Custom inspection functions on objects
版本历史
| 版本 | 变更 |
|---|---|
| v17.3.0, v16.14.0 | 添加了检查参数以提高互操作性。 |
| v0.1.97 | 新增于: v0.1.97 |
对象也可以定义自己的 [util.inspect.custom](depth, opts, inspect) 函数,util.inspect() 将在检查对象时调用并使用其结果。
\Objects may also define their own
[util.inspect.custom](depth, opts, inspect) function,
which util.inspect() will invoke and use the result of when inspecting
the object.
import { inspect } from 'node:util'; class Box { constructor(value) { this.value = value; } [inspect.custom](depth, options, inspect) { if (depth < 0) { return options.stylize('[Box]', 'special'); } const newOptions = Object.assign({}, options, { depth: options.depth === null ? null : options.depth - 1, }); // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); const inner = inspect(this.value, newOptions) .replace(/\n/g, `\n${padding}`); return `${options.stylize('Box', 'special')}< ${inner} >`; } } const box = new Box(true); console.log(inspect(box)); // "Box< true >"const { inspect } = require('node:util'); class Box { constructor(value) { this.value = value; } [inspect.custom](depth, options, inspect) { if (depth < 0) { return options.stylize('[Box]', 'special'); } const newOptions = Object.assign({}, options, { depth: options.depth === null ? null : options.depth - 1, }); // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); const inner = inspect(this.value, newOptions) .replace(/\n/g, `\n${padding}`); return `${options.stylize('Box', 'special')}< ${inner} >`; } } const box = new Box(true); console.log(inspect(box)); // "Box< true >"
自定义的 [util.inspect.custom](depth, opts, inspect) 函数通常返回一个字符串,但也可能返回一个由 util.inspect() 相应格式化的任何类型的值。
\Custom [util.inspect.custom](depth, opts, inspect) functions typically return
a string but may return a value of any type that will be formatted accordingly
by util.inspect().
import { inspect } from 'node:util'; const obj = { foo: 'this will not show up in the inspect() output' }; obj[inspect.custom] = (depth) => { return { bar: 'baz' }; }; console.log(inspect(obj)); // "{ bar: 'baz' }"const { inspect } = require('node:util'); const obj = { foo: 'this will not show up in the inspect() output' }; obj[inspect.custom] = (depth) => { return { bar: 'baz' }; }; console.log(inspect(obj)); // "{ bar: 'baz' }"