I'm curious about the way Node.js prints objects through console.log(object).
我很好奇Node.js通过console.log(对象)打印对象的方式。
I have the following code (from Learning Javascript Design Patterns book) under a file constructor.js
我在文件constructor.js下面有以下代码(来自Learning Javascript Design Patterns一书)
var defineProp = function(obj, key, value){
var config = {
value: value,
writable: true,
configurable: true
};
Object.defineProperty(obj, key, config );
}
var person = Object.create(Object.prototype);
defineProp(person, "car", "Delorean");
defineProp(person, "dateOfBirth", "1981");
defineProp(person, "hasBeard", false);
console.log(person); //This prints {} in Node.js
Running with that code with >node constructor.js
prints an empty object. Chrome however, prints what I would expect if I run the code inside an HTML file.
使用> node constructor.js运行该代码将打印一个空对象。然而,如果我在HTML文件中运行代码,Chrome会打印出我所期望的内容。
console.log(person); //Chrome prints Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false}
Note: I can still print the attributes (such as console.log(person.car)
) under Node, just not the object itself (such as console.log(person)
)
注意:我仍然可以在Node下打印属性(例如console.log(person.car)),而不是对象本身(例如console.log(person))
Why is this? Do Chrome and Node use separate prototypes for the console object, even though they share the same javascript engine?
为什么是这样? Chrome和Node是否为控制台对象使用单独的原型,即使它们共享相同的JavaScript引擎?
1 个解决方案
#1
4
console.log()
in node utilizes util.inspect()
, which uses Object.keys()
on objects, which returns only own enumerable properties. Also, by default, Object.defineProperty()
sets enumerable: false
if you do not explicitly set it to true
.
node.log()在节点中使用util.inspect(),它在对象上使用Object.keys(),它只返回自己的可枚举属性。此外,默认情况下,Object.defineProperty()设置可枚举:如果未将其显式设置为true,则设置为false。
#1
4
console.log()
in node utilizes util.inspect()
, which uses Object.keys()
on objects, which returns only own enumerable properties. Also, by default, Object.defineProperty()
sets enumerable: false
if you do not explicitly set it to true
.
node.log()在节点中使用util.inspect(),它在对象上使用Object.keys(),它只返回自己的可枚举属性。此外,默认情况下,Object.defineProperty()设置可枚举:如果未将其显式设置为true,则设置为false。