Javascript Object Prototype with function vs object

50 views Asked by At

Normally we can prototype by doing this:

HTMLElement.prototype.myFunc = function(){...}

My question is, is it o.k to do:

var myObj = {
    foo:function(){...},
    bar:function(){...}
}
HTMLElement.prototype.myFunc = myObj;

The above does work, but is it safe/efficient to do it this way? what are the pros/cons? Any suggestions are very much appreciated. thanks.

1

There are 1 answers

0
CertainPerformance On

I don't think either method is a good idea, because it mutates the built-in prototypes, which can cause problems. Other code on the page may well not be expecting myFunc to exist on HTMLElement.prototype. The more complicated your page is, and the more libraries you include, the more fragile your code becomes when you change common objects that aren't supposed to be changed. Even worse, what if some other code on the page follows similarly bad practices and tries to add HTMLElement.prototype.myFunc itself? Then your page will (almost certainly) break.

Similarly, a few sites which mutated the built-in prototypes are what caused the Array.prototype.flatten and Array.prototype.contains proposals to fail - they had to be renamed to Array.prototype.flat and Array.prototype.includes respectively after it was found that a few sites following bad practices broke as a result. This situation is not desirable. Best to avoid changing built-in objects, unless the changes are adding spec-compliant properties/methods that modern browsers already have, like polyfills do.

Consider a different method if possible, perhaps like jQuery does it - instead of mutating HTMLElement.prototype, you could pass the element through a wrapper function, which returns an object which has foo and bar methods.