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

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

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

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

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


当前回答

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

其他回答

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

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

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

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中

class Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

似乎对我有用。

我做了这个。

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