Javascript的“Object.getOwnPropertyNames”缺少属性?

时间:2013-10-06 03:42:01

标签: javascript prototype javascript-objects

我喜欢Object.getOwnPropertyNames方法。它似乎是一个从JS shell中学习对象的有用工具。

令我疯狂的是,getOwnPropertyNames似乎缺少一些(注意:在我的测试中,我运行的是ECMA 5实现 - 谷歌Chrome版本28.0.1500.95)。

以下是一个例子:

> var x= []
undefined
> x.constructor
function Array() { [native code] }
> Object.getOwnPropertyNames(x)
["length"]

很明显,x有很多属性! (例如https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

> x.push
function push() { [native code] }
> x.pop
function pop() { [native code] }

任何人都可以帮忙解释这里发生了什么吗?谢谢! :d

编辑:好的!我看到getOwnPropertyNames只获取手头对象的属性名称。有没有一种简单的方法来获得继承属性?或者也许唯一的方法是遍历object.constructor.prototype .__ proto __?

1 个答案:

答案 0 :(得分:4)

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

不推荐使用__proto__属性,不应使用该属性。应使用Object.getPrototypeOf代替__proto__ getter来确定对象的[[Prototype]]。

> x = [];
[]
> Object.getOwnPropertyNames(Object.getPrototypeOf(x));
["length", "constructor", "toString", "toLocaleString", "join", "pop", "push", "concat",
 "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", "some", 
 "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf