我想在类中实现常量,因为在代码中定位它们是有意义的。
到目前为止,我一直在用静态方法实现以下工作:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能会摆弄原型,但许多人建议不要这样做。
在ES6类中有更好的实现常量的方法吗?
我想在类中实现常量,因为在代码中定位它们是有意义的。
到目前为止,我一直在用静态方法实现以下工作:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能会摆弄原型,但许多人建议不要这样做。
在ES6类中有更好的实现常量的方法吗?
当前回答
也许把你所有的常量都放在一个冻结的对象里?
class MyClass {
constructor() {
this.constants = Object.freeze({
constant1: 33,
constant2: 2,
});
}
static get constant1() {
return this.constants.constant1;
}
doThisAndThat() {
//...
let value = this.constants.constant2;
//...
}
}
其他回答
我做了这个。
class Circle
{
constuctor(radius)
{
this.radius = radius;
}
static get PI()
{
return 3.14159;
}
}
PI的值被保护不被改变,因为它是一个函数返回的值。你可以通过Circle.PI访问它。任何对它的赋值尝试都被简单地丢弃,其方式类似于试图通过[]对字符串字符进行赋值。
您可以使用ES6类的一个奇怪特性创建在类上定义静态常量的方法。因为静态数据是由它们的子类继承的,你可以这样做:
const withConsts = (map, BaseClass = Object) => {
class ConstClass extends BaseClass { }
Object.keys(map).forEach(key => {
Object.defineProperty(ConstClass, key, {
value: map[key],
writable : false,
enumerable : true,
configurable : false
});
});
return ConstClass;
};
class MyClass extends withConsts({ MY_CONST: 'this is defined' }) {
foo() {
console.log(MyClass.MY_CONST);
}
}
可以使用import *作为语法。虽然不是类,但它们是真正的const变量。
Constants.js
export const factor = 3;
export const pi = 3.141592;
index.js
import * as Constants from 'Constants.js'
console.log( Constants.factor );
class Whatever {
static get MyConst() { return 10; }
}
let a = Whatever.MyConst;
似乎对我有用。
这里还有一种方法
/* 在类中声明常量的另一种方式是, 注意——常量必须在定义类之后声明 * / 类汽车{ / /其他方法 } 汽车。CONSTANT1 = "const1"; 汽车。CONSTANT2 = "const2"; console.log (Auto.CONSTANT1) console.log (Auto.CONSTANT2);
注意-顺序很重要,你不能有上面的常量
使用
console.log(Auto.CONSTANT1);