我想在class
中实现常量,因为这是在代码中找到它们的意义所在。
到目前为止,我一直在使用静态方法实现以下解决方法:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
我知道有可能摆弄原型,但许多人建议不要这样做。
有没有更好的方法在ES6类中实现常量?
这里有一些你可以做的事情:
从模块中导出const
。根据您的使用情况,您可以:
export const constant1 = 33;
并在必要时从模块导入。或者,基于静态方法的想法,你可以声明一个static
get accessor:
const constant1 = 33,
constant2 = 2;
class Example {
static get constant1() {
return constant1;
}
static get constant2() {
return constant2;
}
}
这样,你就不需要括号:
const one = Example.constant1;
然后,如你所说,因为class
只是一个函数的语法糖,你可以添加一个不可写的属性,如下所示:
class Example {
}
Object.defineProperty(Example, 'constant1', {
value: 33,
writable : false,
enumerable : true,
configurable : false
});
Example.constant1; // 33
Example.constant1 = 15; // TypeError
如果我们可以做以下事情可能会很好:
class Example {
static const constant1 = 33;
}
但不幸的是,这个class property syntax仅在ES7提案中,即便如此也不允许将const
添加到该物业。
我正在使用babel
,以下语法对我有用:
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"]
}
更新:
目前使用stage-2
class Whatever {
static get MyConst() { return 10; }
}
let a = Whatever.MyConst;
似乎为我工作。
在this document它说:
(故意)没有直接声明方式来定义原型数据属性(方法除外)类属性或实例属性
这意味着故意这样。
也许你可以在构造函数中定义一个变量?
constructor(){
this.key = value
}
也可以在类(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
试图改变类将给你一个软失败(不会抛出任何错误,它将没有任何效果)。
也许只是将所有常量放在一个冻结的对象中?
class MyClass {
constructor() {
this.constants = Object.freeze({
constant1: 33,
constant2: 2,
});
}
static get constant1() {
return this.constants.constant1;
}
doThisAndThat() {
//...
let value = this.constants.constant2;
//...
}
}
像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;
}
您可以使用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);
}
}
这是您可以采取的另一种方式
/*
one more way of declaring constants in a class,
Note - the constants have to be declared after the class is defined
*/
class Auto{
//other methods
}
Auto.CONSTANT1 = "const1";
Auto.CONSTANT2 = "const2";
console.log(Auto.CONSTANT1)
console.log(Auto.CONSTANT2);
注意 - 订单很重要,你不能拥有上面的常量
用法console.log(Auto.CONSTANT1);