Object.prototype在Node中返回空对象 [英] Object.prototype returns empty object in Node

查看:137
本文介绍了Object.prototype在Node中返回空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在浏览器控制台中执行 Object.prototype 时,我获得了 Object.prototype 。这是预期的,但是当我在NodeJS终端中执行完全相同的操作时,我得到一个空对象 {} 。有人可以解释一下为什么会这样吗?我附上了两者的截图。



解决方案

这是因为节点中的console.log()使用了util.inspect(),它使用了Object。对象上的keys(),它只返回可枚举的属性。并且 Object.prototype 包含非可枚举属性,这就是它返回空节点的原因。



类似的行为可以是在下面的代码片段中观察到,当我们 console.log(Object.prototype)时,它会记录一个空的 {} ;



  console.log(Object.prototype);  



但是当我们在 Object.prototype中显式定义一个可枚举属性时它记录包含该属性的对象:



  Object。 defineProperty(Object.prototype,'property1',{value:42,enumerable:true}); console.log(Object.prototype) 



Reference


While I execute Object.prototype in browser console, i am getting all the properties and methods available inside Object.prototype. This is as expected but when i am executing exactly the same thing in NodeJS terminal I am getting an empty object {}. Could anyone please explain me why its like this? I have attached screenshots of both.

解决方案

It is because the console.log() in node use util.inspect(), which uses Object.keys() on objects, and it returns enumerable properties only. And Object.prototype contains non-enumerable properties, that is why it returns empty node.

Similar behavior can be observed in the below snippet, when we console.log(Object.prototype) it logs an empty {};

console.log(Object.prototype);

But when we explicitly define an enumerable property in Object.prototype it logs an object containing that property :

Object.defineProperty(Object.prototype, 'property1', {
  value: 42,
  enumerable : true
});
console.log(Object.prototype)

For Reference

这篇关于Object.prototype在Node中返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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