Javascript 在 ES6 类中声明静态常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32647215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring static constants in ES6 classes?
提问by Jér?me Verstrynge
I want to implement constants in a class
, because that's where it makes sense to locate them in the code.
我想在 a 中实现常量class
,因为在代码中定位它们是有意义的。
So far, I have been implementing the following workaround with static methods:
到目前为止,我一直在使用静态方法实现以下解决方法:
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
I know there is a possibility to fiddle with prototypes, but many recommend against this.
我知道有可能摆弄原型,但许多人建议不要这样做。
Is there a better way to implement constants in ES6 classes?
有没有更好的方法在 ES6 类中实现常量?
回答by CodingIntrigue
Here's a few things you could do:
您可以执行以下操作:
Export a const
from the module. Depending on your use case, you could just:
const
从模块中导出 a 。根据您的用例,您可以:
export const constant1 = 33;
And import that from the module where necessary. Or, building on your static method idea, you could declare a static
get accessor:
并在必要时从模块导入。或者,基于您的静态方法想法,您可以声明一个static
get 访问器:
const constant1 = 33,
constant2 = 2;
class Example {
static get constant1() {
return constant1;
}
static get constant2() {
return constant2;
}
}
That way, you won't need parenthesis:
这样,您就不需要括号:
const one = Example.constant1;
Then, as you say, since a class
is just syntactic sugar for a function you can just add a non-writable property like so:
然后,正如你所说,由于 aclass
只是一个函数的语法糖,你可以像这样添加一个不可写的属性:
class Example {
}
Object.defineProperty(Example, 'constant1', {
value: 33,
writable : false,
enumerable : true,
configurable : false
});
Example.constant1; // 33
Example.constant1 = 15; // TypeError
It may be nice if we could just do something like:
如果我们可以做这样的事情可能会很好:
class Example {
static const constant1 = 33;
}
But unfortunately this class property syntaxis only in an ES7 proposal, and even then it won't allow for adding const
to the property.
但不幸的是,此类属性语法仅在 ES7 提案中,即使如此,它也不允许添加const
到属性中。
回答by Benny Jobigan
class Whatever {
static get MyConst() { return 10; }
}
let a = Whatever.MyConst;
Seems to work for me.
似乎对我有用。
回答by borracciaBlu
I'm using babel
and the following syntax is working for me:
我正在使用babel
并且以下语法对我有用:
class MyClass {
static constant1 = 33;
static constant2 = {
case1: 1,
case2: 2,
};
// ...
}
MyClass.constant1 === 33
MyClass.constant2.case1 === 1
Please consider that you need the preset "stage-0"
.
To install it:
请考虑您需要预设"stage-0"
。
要安装它:
npm install --save-dev babel-preset-stage-0
// in .babelrc
{
"presets": ["stage-0"]
}
Update:
更新:
currently use stage-3
目前使用 stage-3
回答by DevAlien
In this documentit states:
在这份文件中,它指出:
There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property
(有意)没有直接的声明方式来定义原型数据属性(方法除外)类属性或实例属性
This means that it is intentionally like this.
这意味着它是故意这样的。
Maybe you can define a variable in the constructor?
也许您可以在构造函数中定义一个变量?
constructor(){
this.key = value
}
回答by rodrigo.botti
It is also possible to use Object.freeze
on you class(es6)/constructor function(es5) object to make it immutable:
也可以Object.freeze
在您的类(es6)/构造函数(es5)对象上使用以使其不可变:
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
Trying to alter the class will give you a soft-fail (won't throw any errors, it will simply have no effect).
试图改变类会给你一个软失败(不会抛出任何错误,它根本没有效果)。
回答by aRIEL
Maybe just put all your constants in a frozen object?
也许只是将所有常量放在一个冻结的对象中?
class MyClass {
constructor() {
this.constants = Object.freeze({
constant1: 33,
constant2: 2,
});
}
static get constant1() {
return this.constants.constant1;
}
doThisAndThat() {
//...
let value = this.constants.constant2;
//...
}
}
回答by jeffwtribble
Like https://stackoverflow.com/users/2784136/rodrigo-bottisaid, I think you're looking for Object.freeze()
. Here's an example of a class with immutable statics:
就像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;
}
回答by user3871424
Here is one more way you can do
这是您可以执行的另一种方法
/*
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);
Note - the Order is important, you cannot have the constants above
注意 - 顺序很重要,你不能有上面的常量
Usage console.log(Auto.CONSTANT1);
用法 console.log(Auto.CONSTANT1);
回答by TbWill4321
You can create a way to define static constants on a class using an odd feature of ES6 classes. Since statics are inherited by their subclasses, you can do the following:
您可以创建一种使用 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);
}
}
回答by Fraser
You can make the "constants" read-only (immutable) by freezing the class. e.g.
您可以通过冻结类将“常量”设为只读(不可变)。例如
class Foo {
static BAR = "bat"; //public static read-only
}
Object.freeze(Foo);
/*
Uncaught TypeError: Cannot assign to read only property 'BAR' of function 'class Foo {
static BAR = "bat"; //public static read-only
}'
*/
Foo.BAR = "wut";