使用nodejs时,我喜欢使用console.log
来查看对象中可用的数据。
但是,这不适用于继承的属性:
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"
给定一个对象,如何查看我可以访问的所有属性?
答案 0 :(得分:1)
您正在为构造函数Person
分配属性。它不与实例共享属性。您需要为Person
的原型添加属性:
Person.prototype.name = "anonymous";
要确定您的对象是否继承自Person
,您可以执行以下操作:
p instanceof Person; // true
您可以通过执行以下操作打印出对象的所有可枚举属性:
for (var key in p) {
console.log(key);
}
答案 1 :(得分:1)
使用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
}
答案 2 :(得分:1)
如果您的目的仅用于调试,则可以查看__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()
可以让您更深入地查看深层嵌套对象。