Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do arrays have no prototype by default?

I was hoping to be able to augment Array.prototype with methods and then call them on any array:

>>> [1, 2, 3].customMethod();

But it appears arrays have no prototype...?

>>> [1, 2, 3].prototype
undefined

Am I missing something here?


It appears my actual problem lies elsewhere: calling [1, 2, 3].customMethod() works, but calling someDomElement.childNodes.customMethod() fails. Is childNodes not a real array?

childNodes.filter is not a function
like image 486
fredoverflow Avatar asked Feb 03 '26 14:02

fredoverflow


1 Answers

prototype is a property of constructor functions, like Array. So Array.prototype exists, but not [1, 2, 3].prototype; Array is a constructor function, while [1, 2, 3] is an array.

You are looking for Object.getPrototypeOf([1, 2, 3]).

Object.getPrototypeOf is an ECMAScript 5 method, and as such may not be present in all browsers. In which case, you can try accessing the __proto__ property, i.e. [1, 2, 3].__proto__, which is an older, nonstandard thing that Object.getPrototypeOf is the new standard version of, or you can use an ES5 shim to ensure that wherever __proto__ is supported, so is Object.getPrototypeOf.

like image 186
Domenic Avatar answered Feb 06 '26 03:02

Domenic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!