Monkey patching constructors in builtin class hierarchies?

Andrea Giammarchi andrea.giammarchi at gmail.com
Tue Oct 24 17:05:34 UTC 2017


if that would be possible, then everyone could just monkey patch `Object`,
right?

I'm not sure I'd be up for it

On Tue, Oct 24, 2017 at 1:56 PM, Boris Cherny <boris at performancejs.com>
wrote:

> 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
>
>
> _______________________________________________
> 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/73880e44/attachment-0001.html>


More information about the es-discuss mailing list