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

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]
See Question&Answers more detail:os

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

1 Answer

Depends on your definition of "work".

There are three main issues with prototype extension.

  • it's global scope so there is name collision
  • If your adding enumerable properties it breaks for .. in
  • Code is confusing to read, is this an ES5 feature or a custom library?

It will work as in, Array.prototype and Array are mutable so you can add the code and call the properties.

However:

Array.prototype.trolls = 42;
for (var k in []) {
  alert(k === "trolls");
}

The above is an example of it breaking for .. in. This is easily solved with

Object.defineProperty(Array.prototype, "trolls", {
  value: ...,
  enumerable: false
});

(ES5 only. Breaks in IE<9. can't be emulated in legacy engines)

or with

for (var k in []) {
  if ([].hasOwnProperty(k)) {
    alert(k === "trolls");
  }
}

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 like pd.extendNatives


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