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

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

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

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

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


当前回答

加上其他答案,您需要导出类以在不同的类中使用。这是它的typescript版本。

/ / Constants.tsx const DEBUG: boolean = true; 导出类常量{ static get DEBUG(): boolean { 返回调试; } } / / Anotherclass.tsx import {Constants} from "Constants"; if (Constants.DEBUG) { console.log(“调试模式”) }

其他回答

也可以在类(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

试图改变类会给你一个软失败(不会抛出任何错误,它根本没有效果)。

我发现的最干净的方法是使用TypeScript -参见如何实现类常量?

class MyClass {
    static readonly CONST1: string = "one";
    static readonly CONST2: string = "two";
    static readonly CONST3: string = "three";
}

给你!

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);
  }
}

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