console.log(object) 如何在后台工作?

How console.log(object) works in background?


我有这个代码:

const obj = {name: 'maro', age: 77}

console.log(obj); // it logs { name: 'maro', age: 77 }

好像很明显!但我想知道 console.log 内部是如何工作的?它调用 "obj" 的哪些方法来获取“{ name: 'maro', age: 77 }”

obj 包含那些属性:

obj.__defineGetter__      obj.__defineSetter__      obj.__lookupGetter__      obj.__lookupSetter__      obj.__proto__             obj.constructor           obj.hasOwnProperty
obj.isPrototypeOf         obj.propertyIsEnumerable  obj.toLocaleString        obj.toString              obj.valueOf    obj.age        obj.name

但是 none 其中 returns "{ 姓名: 'maro', 年龄: 77 }"!

甚至obj.toString()returns'[object Object]'

如果没记错的话是obj.valueOf()。这是文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

如果您需要姓名 'maro' 和年龄 77,则需要使用 obj.name 和 obj.age...

如您在 Node.js console.log documentation, it uses, behind the scenes, util.format 中看到的那样格式化其输出。

根据util.format documentation, it returns a string representation of an object with generic JavaScript object formatting, similar to util.inspect

你可以看到它的实际实现,至少 Node.js,在这里:https://github.com/nodejs/node/blob/75dc8938a40100a53323ed87159a1ab2f149ceca/lib/internal/util/inspect.js#L1567。祝您阅读这段代码愉快:)

您可以使用 valueOf()。

const object1 = {name:"ankit",age:27}
console.log(object1.valueOf());

Note: Objects in string contexts convert via the toString() method, which is different from String objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.