Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ECMAScript 2015(ECMAScript 6) have class initializer?

I've looked in ECMAScript 2015 recently.
Does ECMAScript 2015 have class initializer?

For example, I tried to write class like a parser;

class URLParser {
    parse(url) {
        let regex = /(https?):\/\/([^\/]+)\/([^\?]*)\?([^#]*)#(.*)/;
        (....)
    }
}

var a = new URLParser();
a.parse('http://example.com/abc');
a.parse('http://example.com/def');
var b = new URLParser();
b.parse('https://sample.net/abc');
b.parse('https://sample.net/def');

This regex is common in class, so I'd like to initialize it only once.
I know to use constructor for reduction of initializing, but affects instance wide.
I'd like to know how to reduct initializing class wide.

Thank you.

like image 819
Akira Koyasu Avatar asked Mar 12 '23 10:03

Akira Koyasu


1 Answers

Nope. There is a proposal for static properties though.

Until then, as always, you can add shared properties to the prototype:

URLParser.prototype.regex = /(https?):\/\/([^\/]+)\/([^\?]*)\?([^#]*)#(.*)/;

and access it inside your method via this.regex.

like image 179
Felix Kling Avatar answered Mar 27 '23 21:03

Felix Kling