I have a question about the properties of the “ultimate parent” of prototypes.
(e.g. Array.prototype
, Object.prototype
, Function.prototype
etc.)
I was trying to figure out which properties these prototypes hold. I knew that arrays held a property of “length” and confirmed this via the following:
console.log("This is hasOwnProperty -- " + Array.prototype.hasOwnProperty('length'));
//true
It of course also stands that an array must also have the property of hasOwnProperty()
However, when trying to create a list of all the properties, it did not work. I tried to create this list via the following:
let objectArr = []; for (let property in Array.prototype) { objectArr.push(property); }; console.log(objectArr);
This only return a set of empty brackets. Any help on how to access a complete list of the properties on the ultimate parent prototypes?
Hello and welcome to the forum
!
That’s because the for...in
loop cannot access the non enumerable properties of an object, in this case Array (or the prototype).
You could use Object.getOwnPropertyNames(Array)
,
Regards!
2 Likes
Thank you! How would you pull in the ones that are not the objects “own” properties?
You mean, including the parents? If so, then You would need to create a function to do something like this:
let count = 0
let obj = Array
let result = []
while (obj.prototype && count < 1000) {
result.push(...Object.getOwnPropertyNames(obj.prototype))
obj = obj.prototype
count++ // Just in case xD
}
console.log(result);
// Expected result:
// [
// 'length',
// 'constructor',
// 'concat',
// 'copyWithin',
// 'fill',
// 'find',
// 'findIndex',
// 'pop',
// 'push',
// 'reverse',
// 'shift',
// 'unshift',
// 'slice',
// 'sort',
// 'splice',
// 'includes',
// 'indexOf',
// 'keys',
// 'entries',
// 'forEach',
// 'filter',
// 'map',
// 'every',
// 'some',
// 'reduce',
// 'reduceRight',
// 'toString',
// 'toLocaleString',
// 'join',
// 'lastIndexOf',
// 'values',
// 'flat',
// 'flatMap'
// ]
2 Likes