【问题标题】:declaration of member variables in ES6 classes [duplicate]ES6类中成员变量的声明[重复]
【发布时间】:2016-03-21 19:42:28
【问题描述】:

我见过在 ES6 中这样声明的成员变量

export class MyClass
{
   x = null;

   constructor()  {
      this.x = 1;
   }

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

并且 babel 似乎可以很好地转换它。

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

【问题讨论】:

  • JS中没有“成员变量”这种东西。而且你看到的不是 ES6,而是 ES8 的一个实验性特性提案。不要使用它。

标签: javascript ecmascript-6


【解决方案1】:

这是ES Class Fields & Static Properties 建议的一部分。 它由 babeljs 支持,plugin。 它是一个 babel stage-1 插件,所以如果你使用的是 stage-1 或 stage-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
       }
    }
    

    我看不出单独声明成员变量有什么价值。您在构造函数中创建它。这应该就是你所需要的

    【讨论】:

      猜你喜欢
      • 2017-08-04
      • 1970-01-01
      • 2013-04-21
      • 2015-04-03
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多