我想在类中实现常量,因为在代码中定位它们是有意义的。

到目前为止,我一直在用静态方法实现以下工作:

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

我知道有可能会摆弄原型,但许多人建议不要这样做。

在ES6类中有更好的实现常量的方法吗?


当前回答

这里还有一种方法

/* 在类中声明常量的另一种方式是, 注意——常量必须在定义类之后声明 * / 类汽车{ / /其他方法 } 汽车。CONSTANT1 = "const1"; 汽车。CONSTANT2 = "const2"; console.log (Auto.CONSTANT1) console.log (Auto.CONSTANT2);

注意-顺序很重要,你不能有上面的常量

使用

console.log(Auto.CONSTANT1);

其他回答

也可以在类(es6)/构造函数(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 Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

似乎对我有用。

在这份文件中,它指出:

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

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

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

constructor(){
    this.key = value
}

给你!

const Status = Object.freeze(class Status {
  static Disabled = 0
  static Live = 1
})

您可以使用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);
  }
}