Since getOwnPropertyNames
可以获得不可枚举的属性,您可以使用它并将其与沿着原型链向上结合起来。
function getAllProperties(obj){
var allProps = []
, curr = obj
do{
var props = Object.getOwnPropertyNames(curr)
props.forEach(function(prop){
if (allProps.indexOf(prop) === -1)
allProps.push(prop)
})
}while(curr = Object.getPrototypeOf(curr))
return allProps
}
console.log(getAllProperties([1,2,3]));
我在 Safari 5.1 上进行了测试并得到了
> getAllProperties([1,2,3])
["0", "1", "2", "length", "constructor", "push", "slice", "indexOf", "sort", "splice", "concat", "pop", "unshift", "shift", "join", "toString", "forEach", "reduceRight", "toLocaleString", "some", "map", "lastIndexOf", "reduce", "filter", "reverse", "every", "hasOwnProperty", "isPrototypeOf", "valueOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "propertyIsEnumerable", "__lookupSetter__"]
Update:稍微重构了代码(添加了空格和大括号,并改进了函数名称):
function getAllPropertyNames(obj) {
var props = [];
do {
Object.getOwnPropertyNames(obj).forEach(function (prop) {
if (props.indexOf(prop) === -1) {
props.push(prop);
}
});
obj = Object.getPrototypeOf(obj);
} while (obj);
return props;
}