I have have seen that three method of array are static methods are static. Array.isArray()
, Array.from()
, Array.of
. I can understand why they are static methods. Because the variable passed to them can also be something other than array. Same is case with Number
and String
.
But I cannot understand that why almost all the methods of Object
are static. Why keys
, entries
,values
etc are not on prototype
.
- Is there any advantage of putting them as static method?
- What problems we would have faced if we had
Object.prototype.keys/entries/values...
The problem with Object methods being on the prototype is that objects in general can have arbitrary key-value pairs. For example, if there was such a thing as
Object.prototype.values
, it could very easily cause confusion when you had an object which you intended to have avalues
property, egIf
Object.prototype.values
were a thing, to use it here, you would have to do something likeBetter for
values
to be a static method to avoid such name collisions.If the properties of your objects could be functions as well, it could be even worse, for example:
Now, if
Object.prototype.values
was a thing, and you sawfoo.values()
in the code, what do you think it would mean? Was the programmer intending to call thevalues
property offoo
(which is what the code would result in), or was the programmer intending to useObject.prototype.values
? It'd be an easy source of bugs and hard-to-read code.Same thing for the other Object static methods - they could easily result in name collisions.