Skip to content
Advertisement

JavaScript: refer to anonymous class static variable

Following this google tutorial on web components, and I like the way the author uses an anonymous class in the customElements.define function call, as it avoids even more brackets when creating an immediately invoked function call.

I am using a static class variable to store the template element, so it’s not queried every time the custom tag is instantiated.

The problem is in connectedCallback I don’t know how to refer to class name since it is an anonymous function. In python one could to type(self), but my research shows that typeof this does not work in JS due to prototype magic.

window.customElements.define('my-uploader', class extends HTMLElement {
    static template = document.getElementById("TEMPLATE_UPLOADER");

    constructor() {
        super(); // always call super() first
    }

    /** Custom Component Reactions **/
    connectedCallback() {
        let shadowRoot = this.attachShadow({mode: "open"});
        shadowRoot.appendChild(document.importNode(ANONYMOUS_NAME.template, true));  // <--- How to refer to the class name here?
    }

How to refer to the class’ ANONYMOUS_NAME in connectedCallback?

Advertisement

Answer

You can either name your class, it’s the cleanest way, or you can use this.constructor to get your static variable value :

window.customElements.define('my-uploader', class extends HTMLElement {
    static template = document.getElementById("TEMPLATE_UPLOADER");

    constructor() {
        super(); // always call super() first
    }

    /** Custom Component Reactions **/
    connectedCallback() {
        let shadowRoot = this.attachShadow({mode: "open"});
        shadowRoot.appendChild(document.importNode(this.constructor.template, true)); 
    }

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement