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.
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
myFuncto exist onHTMLElement.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 addHTMLElement.prototype.myFuncitself? Then your page will (almost certainly) break.Similarly, a few sites which mutated the built-in prototypes are what caused the
Array.prototype.flattenandArray.prototype.containsproposals to fail - they had to be renamed toArray.prototype.flatandArray.prototype.includesrespectively 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 hasfooandbarmethods.