Google JavaScript Style Guide advises against extending the Array.prototype
. However, I used Array.prototype.filter = Array.prototype.filter || function(...) {...}
as a way to have it (and similar methods) in browsers where they do not exist. MDN actually provides similar example.
I am aware about Object.prototype
issues, but Array
is not a hash table.
What issues may arise while extending Array.prototype
that made Google advise against it?
Extending the JavaScript built-in object is not a good idea because if browser/JS has decided that they will provide the same method that you have extended, then your method will be override and the JS implementation (which may be difference from yours) would take over.
We can extend the standard Array class and add new methods or redefine the existing ones. The of method on the new extended class creates a new extended array. The standard array methods like filter and map called on extended array return extended arrays.
You should use prototypes if you wish to declare a "non-static" method of the object. var myObject = function () { }; myObject.
The JavaScript array prototype constructor is used to allow to add new methods and properties to the Array() object. If the method is constructed, then it will available for every array. When constructing a property, All arrays will be given the property, and its value, as default.
Most people missed the point on this one. Polyfilling or shimming standard functionality like Array.prototype.filter
so that it works in older browsers is a good idea in my opinion. Don't listen to the haters. Mozilla even shows you how to do this on the MDN. Usually the advice for not extending Array.prototype
or other native prototypes might come down to one of these:
for..in
might not work properlyHere are my responses:
for..in
on Array's usually. If you do you can use hasOwnProperty
to make sure it's legit.Array.prototype.filter
.Object.keys
to IE7. It seemed to stop working under certain circumstances. Your mileage may vary.Check out these references:
Good luck!
I'll give you the bullet points, with key sentences, from Nicholas Zakas' excellent article Maintainable JavaScript: Don’t modify objects you don’t own:
Basically, don't do it. Even if your project is never going to be used by anyone else, and you're never going to import third party code, don't do it. You'll establish a horrible habit that could be hard to break when you start trying to play nice with others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With