我想在类中实现常量,因为在代码中定位它们是有意义的。
到目前为止,我一直在用静态方法实现以下工作:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能会摆弄原型,但许多人建议不要这样做。
在ES6类中有更好的实现常量的方法吗?
我想在类中实现常量,因为在代码中定位它们是有意义的。
到目前为止,我一直在用静态方法实现以下工作:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能会摆弄原型,但许多人建议不要这样做。
在ES6类中有更好的实现常量的方法吗?
当前回答
class Whatever {
static get MyConst() { return 10; }
}
let a = Whatever.MyConst;
似乎对我有用。
其他回答
给你!
const Status = Object.freeze(class Status {
static Disabled = 0
static Live = 1
})
如果试图将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;
似乎对我有用。
我做了这个。
class Circle
{
constuctor(radius)
{
this.radius = radius;
}
static get PI()
{
return 3.14159;
}
}
PI的值被保护不被改变,因为它是一个函数返回的值。你可以通过Circle.PI访问它。任何对它的赋值尝试都被简单地丢弃,其方式类似于试图通过[]对字符串字符进行赋值。
也可以在类(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
试图改变类会给你一个软失败(不会抛出任何错误,它根本没有效果)。