[英]Node.js console.log(object) prints empty object
I'm curious about the way Node.js prints objects through console.log(object). 我很好奇Node.js通过console.log(object)打印对象的方式。
I have the following code (from Learning Javascript Design Patterns book) under a file constructor.js 我在文件builder.js下有以下代码(来自“学习Javascript设计模式”书)
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. 使用>node constructor.js
与该代码一起运行将打印一个空对象。 Chrome however, prints what I would expect if I run the code inside an HTML file. 但是,如果我在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引擎,它们也为控制台对象使用单独的原型吗?
console.log()
in node utilizes util.inspect()
, which uses Object.keys()
on objects, which returns only own enumerable properties . 节点中的console.log()
利用util.inspect()
,该util.inspect()
Object.keys()
在对象上使用Object.keys()
,该对象仅返回自己的可枚举属性 。 Also, by default , Object.defineProperty()
sets enumerable: false
if you do not explicitly set it to true
. 另外, 默认情况下 , Object.defineProperty()
设置enumerable: false
如果未将其显式设置为true
, Object.defineProperty()
enumerable: false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.