[英]Javascript - List all properties/methods from an object
I know that an object literal can have its keys listed by using Object.keys()
method. 我知道可以使用
Object.keys()
方法列出对象文字的键。 But what about an object that was created through a constructor function? 但是通过构造函数创建的对象呢?
function Foo () {}
Foo.prototype.bar = 'bar';
Foo.prototype.baz = 'baz';
var foo = new Foo();
console.log(Object.keys(foo).join(', ')); // returns ''
console.log(Object.getOwnPropertyNames(foo).join(', ')); // returns ''
Object.keys
will only get own enumerable properties, and getOwnPropertyNames
will only get own properties (even if not enumerable). Object.keys
将仅拥有自己的可枚举属性,而getOwnPropertyNames
将仅拥有自己的属性(即使不可枚举)。 Neither of them will give you the names of properties inherited from the prototype (or its prototype, or its , ...). 他们都不会给你从原型继承属性的名称(或它的原型,或者它的 ...)。
If you only care about enumerable properties, see trincot's answer . 如果您只关心可枚举的属性, 请参见trincot的答案 。
If you want all of them,¹ even if they're not enumerable, you have to loop through the prototype chain: 如果您想全部使用它们,¹即使它们不是无法枚举的,也必须遍历原型链:
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));
In that example, I stopped when we reached Object.prototype
, but of course you could keep going until you hit null
instead: 在该示例中,当我们到达
Object.prototype
时,我停了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));
¹ "If you want all of them..." Note that in the above, we haven't tried to get properties that are named by Symbols instead of strings. ¹ “如果要全部使用它们……”请注意,在上文中,我们并未尝试获取由Symbols而不是字符串命名的属性。 If we did, we'd use
getOwnPropertySymbols
as well as getOwnPropertyNames
. 如果这样做,我们将使用
getOwnPropertySymbols
以及getOwnPropertyNames
。
You can use a for
loop: 您可以使用
for
循环:
function Foo () {} Foo.prototype.bar = 'bar'; Foo.prototype.baz = 'baz'; var foo = new Foo(); for (var key in foo) console.log(key, foo[key]);
Note that this has limitations. 请注意,这有局限性。 Some properties can be made non-enumerable, and will then not be included.
某些属性可以设为不可枚举,然后将不包括在内。 This is for instance the case for the
length
property of arrays: 例如,数组的
length
属性就是这种情况:
var a = [1, 2]; for (var key in a) console.log(key, a[key]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.