Possible Duplicate:
Is it an anti-pattern to modify JavaScript's built-in prototypes?
I just learned that it’s possible to modify the JavaScript core objects, but the same article that told me how to do it suggested that I never should.
Is it a bad thing to modify a core JS object? If so, what problems could this cause?
As an example, here’s a modification of the Array object that gives me an easy way to search for a given value in an array:
Array.prototype.search = function(val){
var i;
for (i = 0; i < this.length; i++){
if (this[i] == val) {
console.log("found: " + val);
return true;
}
}
console.log("didn't find it");
return false;
};
Here’s the article: Advanced Javascript: Objects, Arrays, and Array-Like objects
Whether is bad or not is quite debatable, I really like the point of view that @kangax gives us in this article:
At first he separates the extension of host and native objects, with host objects there are no guarantees, there’s no a spec, and they have no rules.
Host objects are those that are provided by the environment, they are not part of the ECMAScript specification, for example DOM objects.
Extending native objects seems “less dangerous”, he explores the problems of enumerability, which seems to be a problem, the
for-instatement enumerates all object properties, inherited or own, if you add a property onObject.prototypefor example, any object used with this statement will show the property name.This statement is often abused to iterate over array objects, while it’s purpose is to enumerate object properties.
At the end, I think the conclusion of this article is that extending native objects to shim standard compliant methods (e.g. ES5 Array methods (map, forEach, reduce, etc)) is encouraged, but extending natives to add custom non-standard compliant methods is discouraged.