Monkey patching constructors in builtin class hierarchies?

Michał Wadas michalwadas at gmail.com
Tue Oct 24 17:07:32 UTC 2017


AFAIR DOM classes are not extensible by any means.



On 24 Oct 2017 6:51 pm, "/#!/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
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171024/dc970fc3/attachment.html>


More information about the es-discuss mailing list