调整自定义对象的 console.log 行为

2024-01-01

有什么方法可以影响 console.log 给出的自定义对象吗? 我尝试覆盖 customObject.prototype.toString 方法,但这不起作用。

有任何想法吗?


之前的答案在较新版本的节点中已被弃用。现在需要实现的方法是符号[util.inspect.custom].

例如:

const util = require('util');

class Custom {
  constructor(foo, bar) {
    this.foo = foo;
    this.bar = bar;
  }

  [util.inspect.custom](depth, opts) {
    return this.foo + this.bar;
  }
}

console.log(new Custom(3, 5)); // Prints '8'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调整自定义对象的 console.log 行为 的相关文章

随机推荐