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

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

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

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

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


当前回答

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

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

其他回答

就像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;
}

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

class MyClass {
    static readonly CONST1: string = "one";
    static readonly CONST2: string = "two";
    static readonly CONST3: string = "three";
}
class Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

似乎对我有用。

我使用巴别塔和以下语法是为我工作:

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"]
}

更新阶段:

它被移到了第三阶段。

更新通天塔7:

根据巴别塔7阶段预设已弃用。

要使用的Babel插件是@babel/plugin-proposal-class-properties。

npm i --save-dev @babel/plugin-proposal-class-properties

{
    "plugins": ["@babel/plugin-proposal-class-properties"]
}

注意:这个插件包含在@babel/preset-env中

给你!

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