在Node.js中自定义输出实例化对象的信息(类似Python的__repr__实现)

443 阅读1分钟

Python中,类有__repr__方法来实现对实例化对象的默认输出进行重写,那么在Node.js中有类似的方法吗?

比方说我们有:

class Example{
    constructor(){
        this.Array = [1,2,3,4];
        this.private_str = "What does the fox say?Dingdingdingdingdingding."
    }
}

如果将示例类Example实例化后输出:

let e = new Example();
console.log(e);

结果如下:

Example {
  Array: [ 1, 2, 3, 4 ],
  private_str: 'What does the fox say?Dingdingdingdingdingding.'
}

但如果我们不想让别人知道狐狸到底说了说了什么,只想把Array部分输出呢?

在旧版本的Node.js中,有一个已经@Deprecated的方法inspect(),但是实测已经用不了了。

我们可以用一种另外的方法来重写类的inspect()方法以实现我们的需求:

使用[util.inspect.custom]来自定义在控制台上的输出。

比方说,我们将我们的代码稍作修改:

const util = require("util")
class Example{
    constructor(){
        this.Array = [1,2,3,4];
        this.private_str = "What does the fox say?Dingdingdingdingdingding."
    }
    [util.inspect.custom](depth, options) {
        return this.Array;
    }
}

let e = new Example();
console.log(e);

输出:

[ 1, 2, 3, 4 ]

大功告成!

注意:此方法不会修改console.dir()的输出