I've read a few articles that suggest extending the built-in objects in JavaScript is a bad idea. Say for example I add a first
function to Array
...
Array.prototype.first = function(fn) {
return this.filter(fn)[0];
};
Great, so now I can get the first element based on a predicate. But what happens when ECMAScript-20xx decides to add first to the spec, and implement it differently? - well, all of a sudden, my code assumes a non-standard implementation, developers lose faith, etc.
So then I decide to create my own type...
var Enumerable = (function () {
function Enumerable(array) {
this.array = array;
}
Enumerable.prototype.first = function (fn) {
return this.array.filter(fn)[0];
};
return Enumerable;
}());
So now, I can pass an array into a new Enumerable, and call first on the Enumerable instance instead. Great! I've respected the ECMAScript-20xx spec, and I can still do what I want it to do.
Then the ES20XX+1 spec is released which introduces an Enumerable
type, which doesn't even have a first method. What happens now?
The crux of this article boils down to this; Just how bad is it to extend the built in types, and how can we avoid implementation collisions in future?
Note: The use of namespaces might be one way to deal with this, but then again, it isn't!
var Collection = {
Enumerable: function () { ... }
};
What happens when the ECMAScript spec introduces Collection
?