尝试打印对象时调用 toString

Nik*_*yal 2 javascript

toString()当我们尝试使用console.logstatement or打印对象时,我试图模仿 Java 的行为来调用该方法alert

目前,我已经尝试过类似的东西

class Some {
    constructor(array = []) {
        this.pvtData = array;
    }

    toString = () => JSON.stringify(this.pvtData);
}

const s = new Some([1, 2, 3]);
console.log(s);
Run Code Online (Sandbox Code Playgroud)

预期的输出应该是

[1,2,3]
Run Code Online (Sandbox Code Playgroud)

但是,我得到的输出为

{
  "toString": () => JSON.stringify(this.pvtData),
  "pvtData": [
    1,
    2,
    3
  ]
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我解决问题并获得所需的输出吗?

注意:
我不想使用console.log(s.toString());. 基本上,console.log声明不应该改变。

T.J*_*der 7

您正在做的事情将起作用,alert因为alert将其参数转换为字符串,但不适用于console.log大多数控制台,因为它们不转换为字符串,它们尝试向您显示对象的表示。

没有console.log跨环境的等效方法。¹ 如果您希望 发生这种情况console.log,则必须覆盖它:

const oldLog = console.log.bind(console);
console.log = (...args) => oldLog(...args.map(String));
Run Code Online (Sandbox Code Playgroud)

现场示例:

const oldLog = console.log.bind(console);
console.log = (...args) => oldLog(...args.map(String));
Run Code Online (Sandbox Code Playgroud)

显然,不要在其他人将要使用的通用库中这样做。不过,在您自己的应用程序或页面中没问题。

或者更好的是,只需使用您自己的日志记录功能来代替包装console.log

class Some {
    constructor(array = []) {
        this.pvtData = array;
    }

    toString = () => JSON.stringify(this.pvtData);
}

const oldLog = console.log.bind(console);
console.log = (...args) => oldLog(...args.map(String));
const s = new Some([1, 2, 3]);
console.log(s);
Run Code Online (Sandbox Code Playgroud)


¹ 在 Node.js 中,控制台曾经寻找一个名为 的方法inspect,但不久前他们停止这样做了。


旁注:通常没有理由制作toString箭头函数。它可以工作(在支持class fields proposal的环境中),但通常没有必要。把它变成一个方法:

class Some {
    constructor(array = []) {
        this.pvtData = array;
    }

    toString() {
        return JSON.stringify(this.pvtData);
    }
}
Run Code Online (Sandbox Code Playgroud)