ES6类中成员变量的声明

时间:2016-03-21 19:42:29

标签: javascript ecmascript-6

我已经看到ES6中的成员变量声明为

export class MyClass
{
   x = null;

   constructor()  {
      this.x = 1;
   }

   write() {
      console.log(this.x);
   }
}

而巴贝尔似乎很顺利。

这是声明成员变量的有效方法吗?

2 个答案:

答案 0 :(得分:2)

我不相信这是正确的。至少,MDN没有提到任何这样的语法。

至于你的例子,让我们逐行完成它。

class MyClass { // Class declaration, all good here
   x = null; // I assume you're telling javascript that the variable x exists?

   constructor()  {
      this.x = 1; // You do that here just fine.
   }

   write() {
      console.log(this.x); // And here we use the variable, after the constructor ran
   }
}

我没有看到单独声明成员变量的任何价值。您可以在构造函数中创建它。这应该就是你需要的全部

答案 1 :(得分:2)

这是ES Class Fields & Static Properties建议的一部分。 它由babeljs支持,plugin。 它是一个babel stage-1插件,所以如果您使用stage-1或stage-0,则支持此功能。