← 中文资源

简体中文版本

inspect.custom 自定义控制台输出

给类定义 [inspect.custom] 方法即可决定 console.log 打印的内容:金额类显示 Money<42.00 USD> 这样的业务形态,内部字段保持原样不受影响。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

Money<42.00 USD>
Money<42.00 USD>
inspect matches: true
fields intact: true

实现说明

底层就是类 Money。 inspect 来自 node:util——Node.js 随运行时自带的核心模块。 顶层就这几处状态:price。

使用要点

  • 无需安装:node:util 随 Node.js 本体提供。
  • 跑完文件,输出里会留下标记——inspect matches:、fields intact:。

常见问题

运行之前需要装什么吗?

什么都不用装:node:util 随 Node.js 本体提供。

核心语句

return `Money<${(this.cents / 100).toFixed(2)} USD>`;

代码示例

import { inspect } from 'node:util';

class Money {
  constructor(cents) {
    this.cents = cents;
  }

  // console.log and util.inspect print this string for the instance
  [inspect.custom]() {
    return `Money<${(this.cents / 100).toFixed(2)} USD>`;
  }
}

const price = new Money(4200);
console.log(price);
console.log(inspect(price));
console.log('inspect matches:', inspect(price) === 'Money<42.00 USD>');
console.log('fields intact:', price.cents === 4200);