DEV Community

Discussion on: You Can Create Private Properties In JS (accessor pattern)

Collapse
jpstone profile image
Justin Stone

"When you're creating Web Components, I don't think you can avoid using prototypes."

Why not? Genuinely curious...

Thread Thread
guitarino profile image
Kirill Shestakov Author

When you're creating Web Components, you have to inherit native HTML element prototype such as HTMLElement or HTMLInputElement, etc. So you'd have to do something like this:

customElements.define('my-element', class extends HTMLElement {
    constructor() {
        super();
        console.log('test');
    }
});
Enter fullscreen mode Exit fullscreen mode

There's really no way to avoid it here with a factory function. You can probably just define all the properties and methods inside the constructor instead of defining it on the prototype (inside class), but there's no benefit to it performance-wise and you can't make the constructor a factory function since you can't return a new object.

Thread Thread
jpstone profile image
Justin Stone

Out of curiosity, why not just do something like:

function myCustomElement() {
  // happy closures go here

  return {
    someTypeOfMetaData,
    someUtilityFunction,
    HTMLElement,
  };
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
guitarino profile image
Kirill Shestakov Author

This won't help you create a custom element, nor register it. Read more about Web Components.