Can I safely extend javascript builtin classes?

2019-01-28 12:57发布

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]

2条回答
疯言疯语
2楼-- · 2019-01-28 13:06

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

查看更多
Rolldiameter
3楼-- · 2019-01-28 13:11

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/

查看更多
登录 后发表回答