[Go Make Things] Web components don't need a constructor()

For years, I've written my web component classes with a constructor() method that calls super() to get access to the parent HTMLElement class's properties…

customElements.define('my-awesome-web-component', class extends HTMLElement {    	constructor () {    		// Inherit properties  		super();    		// The rest of your code...    	}    });  

For my demo projects, I often do all the things in the constructor().

But with Kelp, my UI library for people who love HTML, I'm initializing my in the connectedCallback() method. This is what the spec recommends, and in certain edge cases (like if you're trying to use the Element.replaceWith() method), it can prevent errors.

customElements.define('my-awesome-web-component', class extends HTMLElement {    	constructor () {    		// Inherit properties  		super();    		// Do nothing else here...  	}    	connectedCallback () {  		// Do ALL THE THINGS here...  	}    });  

But when I ran Biome, my linter of choice, on my new table of contents component, I learned that if you're not doing anything in your constructor(), you don't need it at all!

// This works just fine!  customElements.define('my-awesome-web-component', class extends HTMLElement {    	connectedCallback () {  		// Do ALL THE THINGS here...  	}    });  

If I had other code in the constructor(), I would need to run the super() method.

But if I omit a constructor() entirely, it's run implicitly as if super() is called. TIL!

Like this? A Go Make Things membership is the best way to support my work and help me create more free content.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+ Lintasme

Related Post:

0 Komentar untuk "[Go Make Things] Web components don't need a constructor()"

Back To Top