我怎样才能看到nodejs中的所有属性(包括inheritance)?

在使用nodejs时,我喜欢使用console.log来查看对象中可用的数据。

但是,这不适用于inheritance的属性:

 var Person = function () {}; Person.prototype.name = "anonymous"; var p = new Person(); console.log(['p', p]); // [ 'p', {} ] // This doesn't even give me a hint that it's inherited from Person! console.log(['typeof p', typeof p]); // [ 'typeof p', 'object' ] console.log(['p.name', p.name]); // "anonymous" 

给定一个对象,如何查看我可以访问的所有属性?

如果你的目的只是为了debugging,你可以检查__proto__对象:

 function Person() {}; Person.prototype.name = "abc"; Person.prototype.smallObj = { name: "abc" }; Person.prototype.deepObj = { one: { two: { three: { four: "4" } } } }; var p = new Person(); console.log(p); // Person {} console.log(p.__proto__); /* Person { name: 'abc', smallObj: { name: 'abc' }, deepObj: { one: { two: [Object] } } } */ var util = require("util"); console.log(util.inspect(p.__proto__, {depth: null})); /* Person { name: 'abc', smallObj: { name: 'abc' }, deepObj: { one: { two: { three: { four: '4' } } } } } */ 

最后一个,使用具有depth选项的util.inspect()将允许您进一步查看深度嵌套的对象。

您正在将属性分配给构造函数Person 。 它不与实例共享属性。 你需要添加属性到Person的原型:

 Person.prototype.name = "anonymous"; 

要找出你的对象是否从Personinheritance,你可以这样做:

 p instanceof Person; // true 

您可以通过执行以下操作打印出对象的所有可枚举属性:

 for (var key in p) { console.log(key); } 

使用Object.getOwnPropertyNames()获取属于对象的所有属性:

 console.log(Object.getOwnPropertyNames(Person)) // [ 'length', 'name', 'arguments', 'caller', 'prototype' ] console.log(Object.getOwnPropertyNames(Object)) // ['length','name','arguments','caller','prototype','keys','create', 'defineProperty','defineProperties','freeze','getPrototypeOf','setPrototypeOf','getOwnPropertyDescriptor','getOwnPropertyNames','is','isExtensible','isFrozen','isSealed','preventExtensions','seal','getOwnPropertySymbols','deliverChangeRecords','getNotifier','observe','unobserve','assign' ] 

您也可以将Object.getOwnPropertyNames()与原型链结合起来:

 var getAllProperties = function (object) { var properties = [] do { Object.getOwnPropertyNames(object).forEach((prop) => { if (!~properties.indexOf(prop)) { properties.push(prop) } }) } while (object = Object.getPrototypeOf(object)) return properties }