I am currently developing a @Component decorator that modifies the constructor of a class to perform additional tasks after it has been instantiated. The functionality is implemented in an init
method, as shown in the code snippet below.
export function Component (Cls) {
function Class (...args) {
let self = new Cls (...args); // (1)
init (self, ...args);
return self;
}
Class.prototype = Cls.prototype;
return Class;
}
Testing this code on a standard class works perfectly fine. Here is an example:
class Base { ... }
@Component
class Core extends Base {
constructor () {
super (); // init is called
}
fx () { console.log ('Core.fx') }
fy () { console.log ('Core.fy') }
}
However, when attempting to decorate a web component, a TypeError: Illegal constructor
error occurs.
@Component
class Core extends HTMLElement {
constructor () {
super ();
}
fx () { console.log ('Core.fx') }
fy () { console.log ('Core.fy') }
}
customElements.define ('x-core', Core);
let coreX = document.createElement ('x-core');
document.body.appendChild (coreX);
The issue arises from the fact that HTMLElement
does not allow direct instantiation through the new operator - referenced as (1) in the initial code listing. Despite this, I require a way to modify the constructor of any class, including custom elements.
Any suggestions?
Environment: Chrome 68 · Babel 7.0.0-beta.51 with babel-plugin-transform-decorators-legacy