javascript - 在 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 中不想做的事情。
解决方案
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
andMap
objects' values are looked up using their iterators.
推荐阅读
- node.js - 如何在 Node.js 中将大型 JSON 对象转换为类似于 console.log() 的字符串
- swift - 快速计时器目标以防止保留周期
- smtp - Gmail SMTP 服务器会定期响应 550 5.4.5 超出每日用户发送配额。n6sm796326oop.48
- javascript - 为什么 chrome 检查器在数组中显示一件事,但在展开时显示另一件事?香草JS
- python - 来自包含节点和连接python的文本文件的邻接矩阵
- python - 我试图比较 int 和 func 并且它给出了一个错误
- java - Google 表格中的数据刷新问题
- android - Android中悬停视图的圆角?
- javascript - 单击轮播指示器并显示相关幻灯片
- reactjs - HTTPS 与 nginx、fastAPI、docker