We know very well that class
of ES6 brought also : static
, get
as well as set
features :
However , it seems that static
keyword is reserved only for Methods :
class Person {
// static method --> No error
static size(){
}
// static attribute --> with Error
static MIN=10;
}
How to be able to write static
attribute within ES6 class to have something like the static attribute MIN
.
We know that we can add the following instruction after class definition :
Person.MIN=10;
However , our scope is to find the way to write this instruction inside class block
We know very well that class
of ES6 brought also : static
, get
as well as set
features :
However , it seems that static
keyword is reserved only for Methods :
class Person {
// static method --> No error
static size(){
}
// static attribute --> with Error
static MIN=10;
}
How to be able to write static
attribute within ES6 class to have something like the static attribute MIN
.
We know that we can add the following instruction after class definition :
Person.MIN=10;
However , our scope is to find the way to write this instruction inside class block
Share Improve this question asked Jul 13, 2016 at 22:32 Abdennour TOUMIAbdennour TOUMI 93.3k42 gold badges267 silver badges269 bronze badges 1-
Maybe you should check
JS
spec and maybe you find a way to send a feature request to crockford. – Morteza Tourani Commented Jul 13, 2016 at 22:40
3 Answers
Reset to default 10You can use static getter:
class HasStaticValue {
static get MIN() {
return 10;
}
}
console.log(HasStaticValue.MIN);
You cannot reach your scope with ES6 unless static getter , however , you may can in ES7.
Anyway, Babel support now the wanted syntax (check http://babeljs.io/) :
class Foo {
bar = 2
static iha = 'string'
}
const foo = new Foo();
console.log(foo.bar, foo.iha, Foo.bar, Foo.iha);
// 2, undefined, undefined, 'string'
You'd need a method to return the attribute, otherwise its only accessible within the class, which defeats the point of what you're trying to do with static.