Static Variable JavaScript ECMA6 [duplicate]

情到浓时终转凉″ 提交于 2019-12-07 20:21:07

问题


I have a JavaScript class following the ECMA6 standard, and I would like to create a static variable in it.

To achieve this I read the following documentation:

  • JavaScript Static keyword MDN
  • Static variables in JavaScript

The first link demonstrates how one can create static methods inside a class in ECMA 6, while the second link demonstrates how you can use prototype and functions to achieve the creation of static variables prior to ECMA6.

None of this is what I want. I am looking for something like this:

class AutoMobile {

    constructor(name, license) {
        //class variables (public)
        this.name = name;
        this.license = license;
    }

   //static variable declaration
   static DEFAULT_CAR_NAME = "Bananas-Benz";
}

However, the previous example wont work because the static keyword is for methods only.

How can I create a static variable inside a class in JavaScript using ECMA6 ?


回答1:


You can achieve this with getters:

class AutoMobile {

  constructor(name, license) {
    //class variables (public)
    this.name = name;
    this.license = license;
  }

  //static variable declaration
  static get DEFAULT_CAR_NAME() {
    return "Bananas-Benz";
  }
}

And access it with:

const defaultCarName = AutoMobile.DEFAULT_CAR_NAME;

Class properties are not supported in ES2015.



来源:https://stackoverflow.com/questions/37480062/static-variable-javascript-ecma6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!