Node.js console.log(object)打印空对象 [英] Node.js console.log(object) prints empty object

查看:53
本文介绍了Node.js console.log(object)打印空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇Node.js通过console.log(object)打印对象的方式.

I'm curious about the way Node.js prints objects through console.log(object).

我在文件builder.js下有以下代码(来自学习Javascript设计模式"书)

I have the following code (from Learning Javascript Design Patterns book) under a file constructor.js

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

> node Constructor.js 中使用该代码运行将打印一个空对象.但是,如果我在HTML文件中运行代码,Chrome会打印出我期望的内容.

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.

console.log(person); //Chrome prints Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false} 

注意:我仍然可以在Node下打印属性(例如 console.log(person.car)),而不是对象本身(例如 console.log(person)))

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))

这是为什么?即使Chrome和Node共享相同的JavaScript引擎,它们也为控制台对象使用了不同的原型吗?

Why is this? Do Chrome and Node use separate prototypes for the console object, even though they share the same javascript engine?

推荐答案

console.log()使用 util.inspect(),其中在对象上使用 Object.keys() ,它仅返回自己的可枚举属性.另外,默认情况下 Object.defineProperty()设置 enumerable:false (如果未明确将其设置为 true ).

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.js console.log(object)打印空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆