在ES6类中声明静态常量?

我想在class实现常量,因为这是在代码中find它们的位置。

到目前为止,我一直在用静态方法实现下面的解决方法:

 class MyClass { static constant1() { return 33; } static constant2() { return 2; } // ... } 

我知道有可能摆弄原型,但是很多人反对这个。

有没有更好的方法来实现ES6类中的常量?

以下是你可以做的一些事情:

模块中导出一个const 。 根据您的使用情况,您可以:

 export const constant1 = 33; 

并在必要时从模块导入。 或者,build立在静态方法的基础上,你可以声明一个static get访问器 :

 const constant1 = 33, constant2 = 2; class Example { static get constant1() { return constant1; } static get constant2() { return constant2; } } 

这样,你不需要括号:

 const one = Example.constant1; 

Babel REPL例子

然后,正如你所说,因为一个class只是一个函数的语法糖,你可以添加一个不可写的属性,如下所示:

 class Example { } Object.defineProperty(Example, 'constant1', { value: 33, writable : false, enumerable : true, configurable : false }); Example.constant1; // 33 Example.constant1 = 15; // TypeError 

如果我们可以这样做,可能会很好:

 class Example { static const constant1 = 33; } 

但不幸的是,这个类的属性语法只是在ES7的build议,即使这样,它不会允许将const添加到属性。

我使用babel ,以下语法适用于我:

 class MyClass { static constant1 = 33; static constant2 = { case1: 1, case2: 2, }; // ... } MyClass.constant1 === 33 MyClass.constant2.case1 === 1 

请考虑您需要预设的"stage-0"
要安装它:

 npm install --save-dev babel-preset-stage-0 // in .babelrc { "presets": ["stage-0"] } 

在这份文件中说:

有(有意)没有直接声明的方式来定义原型数据属性(方法除外)类属性或实例属性

这意味着它是故意的这样。

也许你可以在构造函数中定义一个variables?

 constructor(){ this.key = value } 

也可以在你的class(es6)/ constructor function(es5)对象上使用Object.freeze来使它不可变:

 class MyConstants {} MyConstants.staticValue = 3; MyConstants.staticMethod = function() { return 4; } Object.freeze(MyConstants); // after the freeze, any attempts of altering the MyConstants class will have no result // (either trying to alter, add or delete a property) MyConstants.staticValue === 3; // true MyConstants.staticValue = 55; // will have no effect MyConstants.staticValue === 3; // true MyConstants.otherStaticValue = "other" // will have no effect MyConstants.otherStaticValue === undefined // true delete MyConstants.staticMethod // false typeof(MyConstants.staticMethod) === "function" // true 

试图改变class级会给你一个软失败(不会抛出任何错误,它将不会有任何影响)。

https://stackoverflow.com/users/2784136/rodrigo-botti说,我认为你正在寻找;Object.freeze() 。 下面是一个不可变静态类的例子:

 class User { constructor(username, age) { if (age < User.minimumAge) { throw new Error('You are too young to be here!'); } this.username = username; this.age = age; this.state = 'active'; } } User.minimumAge = 16; User.validStates = ['active', 'inactive', 'archived']; deepFreeze(User); function deepFreeze(value) { if (typeof value === 'object' && value !== null) { Object.freeze(value); Object.getOwnPropertyNames(value).forEach(property => { deepFreeze(value[property]); }); } return value; } 

这是你可以做的另一种方法

 /* one more way of declaring constants in a class, Note - the constants have to be declared after the class is defined */ class Auto{ //other methods } Auto.CONSTANT1 = "const1"; Auto.CONSTANT2 = "const2"; console.log(Auto.CONSTANT1) console.log(Auto.CONSTANT2);