ES6 class variable alternatives

前端 未结 15 2327
长发绾君心
长发绾君心 2020-11-22 06:04

Currently in ES5 many of us are using the following pattern in frameworks to create classes and class variables, which is comfy:



        
15条回答
  •  没有蜡笔的小新
    2020-11-22 06:20

    As Benjamin said in his answer, TC39 explicitly decided not to include this feature at least for ES2015. However, the consensus seems to be that they will add it in ES2016.

    The syntax hasn't been decided yet, but there's a preliminary proposal for ES2016 that will allow you to declare static properties on a class.

    Thanks to the magic of babel, you can use this today. Enable the class properties transform according to these instructions and you're good to go. Here's an example of the syntax:

    class foo {
      static myProp = 'bar'
      someFunction() {
        console.log(this.myProp)
      }
    }
    

    This proposal is in a very early state, so be prepared to tweak your syntax as time goes on.

提交回复
热议问题