Getting class name directly from class
The previous answers explained that someClassInstance.constructor.name works fine, but if you need to programmatically convert the class name to a string and don’t want to create an instance for this, remember that:
typeof YourClass === "function"
And since each function has a name property, another good way to get a string with your class name is to simply do:
YourClass.name
The following is a good example of why this is useful.
Download web components
As the MDN documentation teaches us, so you download the 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 class after the component tag itself, it would be nice to write a helper function that all your components could use to register. So here is this function:
function registerComponent(componentClass) { const componentName = upperCamelCaseToSnakeCase(componentClass.name); customElements.define(componentName, componentClass); }
So all you have to do is:
registerComponent(YourComponent);
This is good because it is less error prone than the component tag record itself. To wrap it, this is upperCamelCaseToSnakeCase() :
// converts 'YourString' into 'your-string' function upperCamelCaseToSnakeCase(value) { return value // first char to lower case .replace(/^([AZ])/, $1 => $1.toLowerCase()) // following upper chars get preceded with a dash .replace(/([AZ])/g, $1 => "-" + $1.toLowerCase()); }
Lucio Paiva Sep 15 '18 at 22:35 2018-09-15 22:35
source share