我想在类中实现常量,因为在代码中定位它们是有意义的。
到目前为止,我一直在用静态方法实现以下工作:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能会摆弄原型,但许多人建议不要这样做。
在ES6类中有更好的实现常量的方法吗?
我想在类中实现常量,因为在代码中定位它们是有意义的。
到目前为止,我一直在用静态方法实现以下工作:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能会摆弄原型,但许多人建议不要这样做。
在ES6类中有更好的实现常量的方法吗?
当前回答
如果试图将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();
其他回答
在这份文件中,它指出:
(有意地)没有直接的声明性方法来定义原型数据属性(方法除外)类属性或实例属性
这意味着它是故意这样的。
也许你可以在构造函数中定义一个变量?
constructor(){
this.key = value
}
这里还有一种方法
/* 在类中声明常量的另一种方式是, 注意——常量必须在定义类之后声明 * / 类汽车{ / /其他方法 } 汽车。CONSTANT1 = "const1"; 汽车。CONSTANT2 = "const2"; console.log (Auto.CONSTANT1) console.log (Auto.CONSTANT2);
注意-顺序很重要,你不能有上面的常量
使用
console.log(Auto.CONSTANT1);
我发现的最干净的方法是使用TypeScript -参见如何实现类常量?
class MyClass {
static readonly CONST1: string = "one";
static readonly CONST2: string = "two";
static readonly CONST3: string = "three";
}
加上其他答案,您需要导出类以在不同的类中使用。这是它的typescript版本。
/ / Constants.tsx const DEBUG: boolean = true; 导出类常量{ static get DEBUG(): boolean { 返回调试; } } / / Anotherclass.tsx import {Constants} from "Constants"; if (Constants.DEBUG) { console.log(“调试模式”) }
也许把你所有的常量都放在一个冻结的对象里?
class MyClass {
constructor() {
this.constants = Object.freeze({
constant1: 33,
constant2: 2,
});
}
static get constant1() {
return this.constants.constant1;
}
doThisAndThat() {
//...
let value = this.constants.constant2;
//...
}
}