获得对象的所有属性(不管是自身的还是继承的,以及是否可枚举),可以使用下面的函数。
function getPropertyNames(obj) {
var props = {};
while(obj) {
Object.getOwnPropertyNames(obj).forEach(function(p) {
props[p] = true;
});
obj = Object.getPrototypeOf(obj);
}
return Object.getOwnPropertyNames(props);
}
上面代码依次获取obj对象的每一级原型对象“自身”的属性,从而获取Obj对象的“所有”属性,不管是否可遍历。
下面是一个例子,列出Date对象的所有属性。
inheritedPropertyNames(Date)
// [
// "caller",
// "constructor",
// "toString",
// "UTC",
// "call",
// "parse",
// "prototype",
// "__defineSetter__",
// "__lookupSetter__",
// "length",
// "arguments",
// "bind",
// "__lookupGetter__",
// "isPrototypeOf",
// "toLocaleString",
// "propertyIsEnumerable",
// "valueOf",
// "apply",
// "__defineGetter__",
// "name",
// "now",
// "hasOwnProperty"
// ]