简体   繁体   English

ECMAScript 2015(ECMAScript 6)是否具有类初始化程序?

[英]Does ECMAScript 2015(ECMAScript 6) have class initializer?

I've looked in ECMAScript 2015 recently. 我最近看过ECMAScript 2015。
Does ECMAScript 2015 have class initializer? ECMAScript 2015是否有类初始化程序?

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 . 并通过this.regex在您的方法中访问它。

At the moment is not possible to create static properties in ES6 classes, but only static methods. 目前无法在ES6类中创建静态属性,只能在静态方法中创建静态属性。


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. 然后在任何地方使用URLParser.regex来访问它。 A better, less verbose, approach would be to take advantage of JS scoping and just put the regex before the class. 一个更好,更简洁的方法是利用JS范围,并将正则表达式放在课前。 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 目前没有在JavaScript中创建static属性的方法,但是,您可以在constructor定义属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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