Monkey patching constructors in builtin class hierarchies?

/#!/JoePea joe at trusktr.io
Tue Oct 24 16:50:28 UTC 2017


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/1b511d1c/attachment.html>


More information about the es-discuss mailing list