ES5/ES6 methods on constructor functions instead of prototype
This old paper by Allen (and others) is probably the best I've seen at explaining the rationale for "static" methods — es3.1%3Arationale_for_es3_1_static_object_methodsaug26.pdf
The Object methods are on the constructor because if they were put on the prototype, they'd show up on every single object in all of JS. The potential for property-name collision would be terrible.
Some methods, like isArray(), aren't very useful if they only show up on the prototype - being able to ask an array if it's an Array is nice, but you'd like to be able to ask any object. Either you instead define Object.prototype.isArray() (and that still doesn't help primitives, or objects with a null prototype), or you stash it somewhere as a plain function, rather than a method. The Array constructor is a convenient and memorable place to do so - it serves as an adequate namespace for the method to avoid polluting the global object.
How would you define Array.isArray on the Array prototype? That'd just fail for everything that is not an array and doesn't implement isArray itself.
Things like Object.keys are reflective, enumerating over the properties of
an object (even more so in ES6) is not something you'd commonly do in the
'application level'. We have Map
s now :)
I'm noticing that many methods added in ES5 and due in ES6 are defined on the type's constructor function instead of on the type's prototype. For example, Object.keys, Object.defineProperty, and Array.isArray.
Is there a reason these were not added to the prototype, i.e. Object.prototype.keys, for consistency?
Best, Oliver