Can I safely extend Javascript builtin classes, like Array
?
I.e. on which browsers/environments will the following not work:
Array.prototype.double = function() { return this.concat(this); }
Array.twice = function(a) { return a.double(); }
Array.twice([1, 2, 3]) # => [1, 2, 3, 1, 2, 3]
Depends on your definition of "work".
There are three main issues with prototype extension.
for .. in
It will work as in,
Array.prototype
andArray
are mutable so you can add the code and call the properties.However:
The above is an example of it breaking
for .. in
. This is easily solved with(ES5 only. Breaks in IE<9. can't be emulated in legacy engines)
or with
Personally I avoid automatically extending natives for these exact reasons. However I think it's perfectly acceptable to have a
.extendNatives
function in your library likepd.extendNatives
Safely, not really - because you can't be sure you're the only one extending them, or that you're actually extending the correct methods (see Prototype - last time I checked, it was extending the builtin classes, which wreaked havoc on others scripts' expectations of the builtins' behavior). Modifying objects you don't own is a path to very tricky territory ("oh, but is this the actual built-in
concat()
, or did some other script change it behind our back?").See e.g. this for a more detailed discussion: http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/