Monkey patching constructors in builtin class hierarchies?

Boris Cherny boris at performancejs.com
Tue Oct 24 16:56:52 UTC 2017


This feels like a problem similar to https://esdiscuss.org/topic/block-scoped-prototype-extensions

> On Oct 24, 2017, at 9:50 AM, /#!/JoePea <joe at trusktr.io> wrote:
> 
> Is it possible to monkey-patch an intermediate constructor of a built-in subclass?
> 
> 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?
> 
> For example:
> 
> ```js
> // monkey-patch the Element constructor somehow so that it logs "patched in Element".
> 
> // then
> class FooBar extends HTMLElement {}
> customElement.define('foo-bar', FooBar)
> new FooBar // "patched in Element"
> ```
> 
> I tried
> 
> ```js
> const OldElement = window.Element
> 
> window.Element = function Element() {
>   const _this = new OldElement
>   console.log("patched in Element")
>   return _this
> }
> 
> window.Element.prototype = OldElement.prototype
> window.Element.prototype.constructor = window.Element
> 
> class FooBar extends HTMLElement {}
> customElements.define('f-b', FooBar)
> new FooBar // does not log "patched in Element"
> ```
> 
> But when I make a new custom element, constructing it seems to use the old Element constructor, as if a non-global reference to the original constructor is kept inside a module so that modifying the global wouldn't have any effect.
> 
> 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?
> 
> 
> /#!/JoePea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171024/ea5da6eb/attachment-0001.html>


More information about the es-discuss mailing list