0

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.

Tunasing
  • 31
  • 4
  • I'm not sure what do you want to do with it tho. I would say extending built-in objects though it's `prototype` is a bad idea for some reason in terms of performance and maintainability. I've found a related post on SO: https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – shotasenga Nov 30 '19 at 03:45
  • No, putting an object on a prototype doesn't work at all. – Bergi Nov 30 '19 at 04:00
  • Please do not extend native objects. If you want to extend other objects, you can use `Object.assign(prototypeOrObjectOfYourObject, { foo(){}, bar(){} }`. – some Nov 30 '19 at 04:02
  • I understand that since 2011, many posts regards prototyping native elements as bad practice, its 2019, and i'm wondering if views on this subject has in any way changed or improved. Or a case of "reading too much stack overflows". – Tunasing Nov 30 '19 at 04:05

1 Answers1

0

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320