Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
627 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:

  1. for..in might not work properly
  2. Someone else might also want to extend Array with the same function name
  3. It might not work properly in every browser, even with the shim.

Here are my responses:

  1. You don't need to use for..in on Array's usually. If you do you can use hasOwnProperty to make sure it's legit.
  2. Only extend natives when you know you're the only one doing it OR when it's standard stuff like Array.prototype.filter.
  3. This is annoying and has bit me. Old IE sometimes has problems with adding this kind of functionality. You'll just have to see if it works in a case by case basis. For me the problem I had was adding Object.keys to IE7. It seemed to stop working under certain circumstances. Your mileage may vary.

Check out these references:

Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...