Question on prototype
:
Why do some Array methods have .prototype
and others don't?
The documentation states "Array.prototype
represents the prototype for the Array
constructor".
I am trying to reconcile this statement with the understanding that prototype
is a property referring to the parent type, since that is how inheritance is achieved.
If the latter is true, then what is the parent type of Array
who "owns" the methods like map()
and indexOf()
?
My main question is the one on the first line.
I am trying to reconcile this statement with the understanding that prototype is a property referring to the parent type, since that is how inheritance is achieved.
No. The prototypical relation to another object (from which properties are inherited) is done via an invisible link, sometimes denoted as [[prototype]]
.
The actual, existing .prototype
property on a constructor function is the object from which all instances that were constructed by that function will inherit.
So the prototype (inheritance) chain of an Array object looks like this:
null
^
|
Object.prototype ---> {hasOwnProperty(), …} // all objects inherit these
^
|
Array.prototype ----> {map(), indexOf(), …} // all arrays inherit these
^
|
{length, 0, 1, 2, …} // an example array
// as if constructed by new Array(5) or [42, 7, 6]
Why do some methods have .prototype and some don't?
The functions that are available on the .prototype
will be inherited by all instances, you can call them directly on them if they were a method of them.
The functions that are placed directly on the constructor function, like Array.isArray
or Array.of
, are not instance-related and "static" so to say. You call them mostly with non-arrays as arguments.
The methods that aren't on the prototype are like "class" methods in some other languages (kind-of; the similarity is superficial). Methods on the prototype are callable from the context of any array instance; methods directly on the constructor are not.
The "length" property is a property of every array instance; there's a "length" property on the constructor function too, but it's meaning is completely different — it tells you how many formal parameters are in the function (the Array function).
The "parent type" of Array, to the extent that such a thing makes sense in JavaScript, is "Object", but that doesn't have anything to do with the methods on the Array prototype.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With