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

Moe*_*ler 9 javascript node.js

有没有办法影响console.log提供自定义对象?我试图覆盖但不起作用的customObject.prototype.toString方法.

有任何想法吗?

Joh*_*yHK 18

在node.js中,console.log调用util.inspect每个参数而不使用格式化占位符.因此,如果您inspect(depth, opts)在对象上定义一个方法,它将被调用以获取该对象的自定义字符串表示形式.

例如:

function Custom(foo) {
    this.foo = foo;
}

Custom.prototype.inspect = function(depth, opts) {
    return 'foo = ' + this.foo.toUpperCase();
};

var custom = new Custom('bar');
console.log(custom);
Run Code Online (Sandbox Code Playgroud)

输出:

foo = BAR

或者使用课程:

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

    inspect(depth, opts) {
        return 'foo = ' + this.foo.toUpperCase();
    }
}

var custom = new Custom('bar');
console.log(custom);
Run Code Online (Sandbox Code Playgroud)

  • 浏览器中是否有任何等效选项? (8认同)
  • 至少从 Node v16+ 开始,这不再有效。请参阅另一个答案。 (4认同)

小智 12

先前的答案已在较新版本的节点中弃用。现在需要实现的方法是符号[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'
Run Code Online (Sandbox Code Playgroud)

  • 如何在浏览器中执行此操作? (4认同)

Kir*_*kov 5

最近 (18) Node.js 版本包含此文档片段作为如何跨 Node 和浏览器执行此操作的示例:

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>
Run Code Online (Sandbox Code Playgroud)