最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add static attribute to ES6 class - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 10

You 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.

发布评论

评论列表(0)

  1. 暂无评论