Monkey patching constructors in builtin class hierarchies?

Boris Zbarsky bzbarsky at
Tue Oct 24 17:52:42 UTC 2017

On 10/24/17 12:50 PM, /#!/JoePea wrote:
> Is it possible to monkey-patch an intermediate constructor of a built-in 
> subclass?

Right now, no.

> For example, suppose I want all `Element` instances in a web app to have 
> new instance properties, is there a way to monkey-patch the Element 
> constructor so that when I make a custom element by extending a subclass 
> of `Element` that the new logic will fire?

If you want to limit this to custom elements you control, in the sense 
of <>, then 
"sort of, yes".  You could just define a class that extends HTMLElement, 
have its constructor do whatever instance-property-setting you want, and 
have all your actual custom element classes extend that one class.

If you want to do this to custom elements you do NOT control, you can 
sort of do it too, using Andrea's suggestion later in this thread: as 
long as your code runs first, you can set your class as 
window.HTMLElement so everyone else is extending you, not the "real" 

> const OldElement = window.Element

This won't work, because Element is not constructible, so all the 
constructor behavior lives in HTMLElement.  But if you did this with 
HTMLElement, I would expect it would work, as in Andrea's suggestion.

> Is there a way to monkey patch a constructor in the middle of a built-in 
> prototype chain or to otherwise inject construction logic to base 
> classes of existing class hierarchies?

Right now, no.


More information about the es-discuss mailing list