我喜欢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__?
最佳答案
根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
原文链接:https://www.f2er.com/js/429822.html不推荐使用__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"]