1

I want to use customElements.define to create web components, but I don't want to use the new class syntax of ES6.

so instead of

class MyClass extends HTMLElement {} 

customElements.define("my-class", MyClass);

I want something like this

var myObj = function(){}
Object.setPrototypeOf(myObj, HTMLElement);

customElements.define("my-obj", myObj);

I tried defining customElement as a plain object instead of a function, but it complains as follows

Uncaught TypeError: Failed to execute 'define' on 'CustomElementRegistry': The callback provided as parameter 2 is not a function.

after setting it to be a function I get the following error

Uncaught TypeError: Failed to construct 'CustomElement': The result must implement HTMLElement interface

I'm a little mystified of what an interface could mean in Javascript. I looked at the property descriptors of both snippets, but couldn't find any property about an interface.

What is it that extends do other than setting the prototype of the object?

Thank you for helping me :)

  • *"What is it that extends do other than setting the prototype of the object?"* It sets the prototype of the `prototype` property of the function and it calls the parent constructor if no own constructor is defined. So essentially your `myObj` function needs to call `HTMLElement` somehow. The duplicate shows how. – Felix Kling Jan 03 '20 at 10:18
  • @FelixKling I also thought of the following solution as a middle ground .You can also run the factory function through something like babeljs.io `function factory() { return class extends HTMLElement{} } var myObj = factory(); myObj.prototype.connectedCallback = function(){ console.log("connected"); } customElements.define("my-obj", myObj);` –  Jan 03 '20 at 14:23

0 Answers0