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

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

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

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

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


当前回答

只需将变量声明为私有并使用get方法检索它们。

class MyClass {

   #myConst = 'Something';

   static #anotherConst = 'Something Else';

   get myConst() {
      return this.#myConst; // instance method
   }

   static get anotherConst() {
      return MyClass.#anotherConst; // static method
   }
}

let myClass = new MyClass();

console.log( myClass.myConst + ' is not ' + MyClass.anotherConst );

用户不能更改原始变量,您可以编写类来使用get方法而不是私有变量本身。

其他回答

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

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

如果试图将const/variable作为类的静态对象;尝试使用散列(#)来定义占位符,而不是使用函数来访问它。

class Region {
    // initially empty, not accessible from outside
    static #empty_region = null; 

    /* 
        Make it visible to the outside and unchangeable 
        [note] created on first call to getter.
    */

    static EMPTY() {
        if (!this.#empty_region)
            this.#empty_region = new Region(0, 0, 0, 0);
        return this.#empty_region;
    }

    #reg = {x0:0, y0:0, x1:0, y1:0};

    constructor(x0, y0, x1, y1) { 
        this.setRegion(x0, y0, x1, y1);
    }

    // setters/getters
}

实现:

let someRegion = Region.EMPTY();

let anotherRegion = Region.EMPTY();
class Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

似乎对我有用。

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

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

如果你喜欢混合和匹配函数和类的语法,你可以在类之后声明常量(常量被“提升”)。注意,Visual Studio Code将很难自动格式化混合语法(尽管它可以工作)。

MyClass { / /…… } MyClass.prototype.consts = { constant1: 33岁 constant2: 32 }; mc = new MyClass(); console.log (mc.consts.constant2);