As far as I have seen any array related method it has to be accessed from its prototype, e.g. Array.prototype.slice
.
Why is the from
method called on Array
object as in Array.from
instead of being called as Array.prototype.from
?
As far as I have seen any array related method it has to be accessed from its prototype, e.g. Array.prototype.slice
.
Why is the from
method called on Array
object as in Array.from
instead of being called as Array.prototype.from
?
It's not in the Array.prototype
because Array
instances do not benefit from this method (it does not use any context). As to why it is on the constructor, that's purely convention. You could have the function floating around in the global scope e.g. ArrayFrom()
but the specification groups related functions under their respective constructor as a convention and as sort of a namespace to avoid collisions.
You can look at Array.from
as a constructor for arrays. The important thing here is that it can create an array from both array-like structures (having array-like properties like indexes and .length
) and also iterables (objects with .next()
or in other words - having a registered iterator).
There is absolutely no point in having the .from()
method attached to the prototype like [1, 2, 3].from()
. What do you expect this method to do exactly in this context? It serves no purpose.
In general, the instance (prototype) methods manipulate a specific already existing instance of an array. Static ones like Array.from()
, Array.of()
and Array.isArray()
don't (and shouldn't) require an instance.
This is true not only for arrays but for general class/prototype design especially in data-structures.
Array.from is a static method that returns array, Array.prototype.slice is a method from the Array prototype and can be called on Arrays.
The reason is that JavaScript uses prototype chain: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
In general, when the method is not found in the instance, it looks into the prototype. If the method is not even there, it looks in the following prototype in the chain and so on. So this is why slice
is found even if it is defined in the prototype.
The second reason is that the prototype is shared by all the instances of that class. So all the arrays share the same prototype - same object. Therefore the method doesn't need to be repeated in every instance and we save some space.
from()
, on the other hand, is class method - you don't need instance to call that method. It is therefore defined directly on the Array class rather than on the prototype (because then it would be instance method).