首页 > 解决方案 > 在 JavaScript ES6 中,如果 console.log() 不调用 obj.toString(),它有什么用?

问题描述

一些相关信息在这个问题中:在标准 JavaScript ES6 环境中,什么时候调用过 .toString()?

通过多态性,toString()是通过 Object 类的接口发送给对象的标准消息(或在对象上调用的标准方法)。

但显然,console.log()不使用它:

// Inside of Node

> let aSet = new Set([1,3,5]);

> aSet.toString()
'[object Set]'

> console.log(aSet);
Set { 1, 3, 5 }

> let aMap = new Map([["foo", 1], ["bar", 2]])

> aMap.toString()
'[object Map]'

> console.log(aMap)
Map { 'foo' => 1, 'bar' => 2 }

那么有什么console.log()用呢?它不是valueOf(),因为valueOf()在这种情况下只返回对象本身,当没有原始值可用时。

“特殊情况”它是什么类并执行不同的操作是非常难看的——因为多态性,在这种情况下,具有标准的“动词”,toString()是应该使用的。找出类是什么并执行不同的操作(例如使用 switch 语句),这正是我们在 OOP 中不想做的事情。

标签: javascriptconsole.log

解决方案


console.log(), along with other console methods, is implementation-dependent.

My answer applies only to Node.js.


After some looking into the internal source files of Node.js, it turned out that in Node (v12), console methods use a common way to display values: the util.formatWithOptions method.

Its internal source is written in JavaScript, and it calls internal formatter functions (located in internal/util/inspect.js), that formats objects based on their type, for example:

  • Primitives are simply stringified.
  • Plain objects are iterated over their properties, to show them.
  • Arrays are iterated over based on their length.
  • Set and Map objects' values are looked up using their iterators.

推荐阅读