Does ECMAScript 2015 (ECMAScript 6) have a class initializer?

I recently looked at ECMAScript 2015.
Is there a class initializer in ECMAScript 2015?

For example, I tried to write a class as 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 regular expression is common in the class , so I would like to initialize it only once.
I know that to use the constructor to reduce initialization, but it affects the instance wide .
I would like to know how to restore class initialization .

Thank.

+4
source share
4 answers

. , .

, , :

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

this.regex.

+3

ES6, .


, :

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

. ,

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

URLParser.regex . , JS . , .

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

class URLParser {
  parse(url) {
    (....)
  }
}
+2

There is no current way to create properties in JavaScript static, however you can simply define a property inconstructor

class URLParser {
    constructor() {
        this.regex = /(https?):\/\/([^\/]+)\/([^\?]*)\?([^#]*)#(.*)/;
    }
    parse(url) {
        this.regex.match(url)
        (...);
    }
}
0
source

All Articles