[JS] – How to create classes with methods that can be accessed directly without a new instance of this class?

For this you should create a class and define its methods as static.

Example Class:

class DateHelper {

    static converterTextForDate(text) {

        if(!/\d{4}-\d{2}-\d{2}/.test(text)) {
            throw new Error('Should be in the format aaaa-mm-dd');
        return new Date(...texto.split('-').map((item, index) 
                                            => item - index % 2));

How to use it ?


How to don’t allow new instances of this class ?

You can return a error in the constructor of this class. Example :

 constructor() {
     throw new Error('You can't use instances of this class');

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s