Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's "Object.getOwnPropertyNames" Missing Properties?

I love the Object.getOwnPropertyNames method. It seems like such a useful tool for learning about objects from within a JS shell.

What's driving me nuts, though, is that getOwnPropertyNames seems to be missing some (Note: in my tests I am running an ECMA 5 implementation—Google Chrome version 28.0.1500.95).

Here's an example:

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

Yet clearly, x has lots of properties! (e.g. 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] }

Can anyone help explain what's going on here? Thanks! :D

Edit: Okay! I see that getOwnPropertyNames only gets the property names of the object at hand. Is there a simple way to get inherited properties? Or perhaps the only way is to traverse through object.constructor.prototype.__proto__?

like image 482
masonjarre Avatar asked Oct 03 '22 18:10

masonjarre


1 Answers

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

The __proto__ property is deprecated and should not be used. Object.getPrototypeOf should be used instead of the __proto__ getter to determine the [[Prototype]] of an object.

> 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

like image 99
Pedro Vitti Avatar answered Oct 07 '22 05:10

Pedro Vitti