Why do some methods have .prototype and others not?

.prototype question: Why do some Array methods have .prototype and others not?

JavaScript Array method names screenshot

the documentation states: " Array.prototype represents a prototype of the Array constructor."

I am trying to reconcile this statement with the understanding that prototype is a property related to the parent type, since this is achieved by inheritance.

If the latter is true, then what is the parent type of Array that owns methods such as map() and indexOf() ?

My main question is the one on the first line.

+7
javascript
source share
3 answers

I am trying to reconcile this statement with the understanding that the prototype is a property related to the parent type, since this is achieved by inheritance.

Not. The prototype relation to another object (from which the properties are inherited) is carried out through an invisible link, sometimes referred to as [[prototype]] .

The actual existing existing .prototype property in the constructor function is the object from which all instances that were built by this function are inherited.

So, the prototype chain (inheritance) of the 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 not?

Functions available in .prototype will be inherited by all instances, you can call them directly on them if they were their method.

Functions that are placed directly above the constructor function, such as Array.isArray or Array.of , are not associated with the instance and, therefore, are β€œstatic”. You call them mainly with non-arrays as arguments.

+5
source share

Methods that are not in the prototype are similar to class methods in some other languages ​​(view, similarity is superficial). Prototype methods are called from the context of any array instance; methods directly on the constructor are not.

The length property is a property of each array instance; There is also a length property for the constructor function, but this value is completely different. it tells you how many formal parameters are in the function (array function).

The "parent type" of the array, as far as it makes sense in JavaScript, is "Object", but it has nothing to do with the Array prototype methods.

+5
source share

Array.prototype.* Methods can be called on array instances and seem to be the "method" of these instances, while Array.* Methods cannot (at least not directly) and instead the object itself must be called from Array .

For example:

 [].concat([]) // calls Array.prototype.concat Array.concat([]) // undefined Array.isArray([]) // calls Array.isArray [].isArray([]) // undefined 
+4
source share

All Articles