简体   繁体   中英

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.

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 .

At the moment is not possible to create static properties in ES6 classes, but only static methods.


But you can attach properties directly to the class, which will emulate static properties:

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

It does not. There is a proposal for class-level declarative initialization, so you could potentially do

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

and then use URLParser.regex everywhere to access it. A better, less verbose, approach would be to take advantage of JS scoping and just put the regex before the class. There's nothing to gain by having the regex attached to the class.

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

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

There is no current way to make static properties in JavaScript, however, you could just define the property in the constructor

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM