Getting class name directly from class
Previous answers explained that someClassInstance.constructor.name
works just fine, but if you need to programmatically convert class name into a string and don't want to create an instance just for that, remember that:
typeof YourClass === "function"
And, since every function has a name
property, another nice way to get a string with your class name is to just do:
YourClass.name
What follows is a good example of why this is useful.
Loading web components
As the MDN documentation teaches us, this is how you load a web component:
customElements.define("your-component", YourComponent);
Where YourComponent
is a class extending from HTMLElement
. Since it is considered good practice to name your component's class after the component tag itself, it would be nice to write a helper function that all your components could use to register themselves. So here's is that function:
function registerComponent(componentClass) {
const componentName = upperCamelCaseToSnakeCase(componentClass.name);
customElements.define(componentName, componentClass);
}
So all you need to do is:
registerComponent(YourComponent);
Which is nice because it's less error-prone than writing the component tag yourself. To wrap it up, this is the upperCamelCaseToSnakeCase()
function:
// converts `YourString` into `your-string`
function upperCamelCaseToSnakeCase(value) {
return value
// first char to lower case
.replace(/^([A-Z])/, $1 => $1.toLowerCase())
// following upper chars get preceded with a dash
.replace(/([A-Z])/g, $1 => "-" + $1.toLowerCase());
}
instance.constructor.name
andclass.name
return the class name in proper ES6. – CataloniasomeClassInstance.constructor.name
will get mangled if you uglify your code. – Pithos.constructor
. – Intake