Object.keys
只会得到自己枚举的属性,并getOwnPropertyNames
只会得到自己性能(即使不枚举)。它们都不会给你从原型(或其原型,或的,...)继承的属性名称。
如果您只关心enumerable属性,see trincot's answer。
如果你想他们的所有,¹即使他们不枚举,您必须通过原型链环:
function getAllPropertyNames(obj) {
var result = [];
while (obj && obj !== Object.prototype) {
result.push.apply(result, Object.getOwnPropertyNames(obj));
obj = Object.getPrototypeOf(obj);
}
return result;
}
function Foo() {}
Foo.prototype.bar = 'bar';
Foo.prototype.baz = 'baz';
var foo = new Foo();
console.log(getAllPropertyNames(foo));
在这个例子中,我停了下来当我们达到Object.prototype
,但当然你可以继续下去,直到你点击null
代替:
function getAllPropertyNames(obj) {
var result = [];
while (obj) {
result.push.apply(result, Object.getOwnPropertyNames(obj));
obj = Object.getPrototypeOf(obj);
}
return result;
}
function Foo() {}
Foo.prototype.bar = 'bar';
Foo.prototype.baz = 'baz';
var foo = new Foo();
console.log(getAllPropertyNames(foo));
¹“如果你想他们的所有 ...”注意,在上面的,我们并没有试图获得由Symbols,而不是字符串命名属性。如果我们这样做了,我们会使用getOwnPropertySymbols
以及getOwnPropertyNames
。
理解的关键是单词'Own'在'getOwnPropertyNames' – trincot