静态变量JavaScript ECMA6 [英] Static Variable JavaScript ECMA6

查看:136
本文介绍了静态变量JavaScript ECMA6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



为了达到这个目的,我阅读了以下文档:





第一个链接演示了如何创建ECMA 6中的类中的静态方法,而第二个链接演示了如何使用原型和函数来实现在ECMA6之前创建静态变量。



这不是我想要的。我正在寻找这样的东西:

  class AutoMobile {

constructor(name,license){
//类变量(public)
this.name = name;
this.license =许可证;
}

//静态变量声明
static DEFAULT_CAR_NAME =Bananas-Benz;
}

然而,以前的例子不会工作,因为 static 关键字仅适用于方法。



如何使用ECMA6在JavaScript中创建一个静态变量?

解决方案

你可以用getter来实现:

  class AutoMobile {

构造函数(名称,许可证){
//类变量(public)
this.name = name;
this.license =许可证;
}

//静态变量声明
static get DEFAULT_CAR_NAME(){
returnBananas-Benz;
}
}

然后访问:

  const defaultCarName = AutoMobile.DEFAULT_CAR_NAME; 

ES2015不支持类属性。


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:

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 ?

解决方案

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.

这篇关于静态变量JavaScript ECMA6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆