由于
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__"]
更新:稍微重构了代码(添加了空格、花括号,并改进了函数名称):
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;
}