user3259983 user3259983 - 1 year ago 32
Javascript Question

Should we always keep copy of JavaScript built-in object's method?

There are loads of functions defined in JavaScript built-in object. For example

and they can be overridden (though it is a bad practice) by simply using

Array.prototype.join = 'test'
, Then all the array will lose the

However, as a developer of open source project, in what way should we view this potential changes to the prototype? It will become a problem because it is very likely we will use these functions more or less to achieve some functionalities.

In jQuery, it will keep a copy of some of those methods:

var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;

But only some of the methods are kept safe, if you read through the source code of jQuery you will notice some
methods are called directly on the String object.

Of course we can always keep a copy of all the methods of built-in JavaScript object but it is so messy. Indeed, it also becomes a problem of execution timing. If the program is executed before the prototype is changed, then it's fine. But it will fail if it is vice versa. So I am more interested to know when jQuery or other libraries they decide to keep a copy of some of the methods, what are their philosophy behind the decision?

Thank you.


As a developer of an open source project, the safest and best thing to do is to pretend that the builtin prototypes are frozen. The practice of extending or modifying them is responsible for far more problems than solutions.

If you need a custom join function, just create it so that it takes a string as the first argument.

function join(string, separator) {
  // ... 

This keeps the prototypes clean and stops you from having to worry about references to overwritten methods.

What you're seeing there in the jQuery example is just aliasing. The methods are being assigned to variables to make them easier to use.

There's no way to code defensively around this, because by the time jQuery loads another script could have already modified the builtin prototypes and the original references would be lost.