ES6 类中成员变量的声明

declaration of member variables in ES6 classes

本文关键字:声明 变量 成员 ES6      更新时间:2023-09-26

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

export class MyClass
{
   x = null;
   constructor()  {
      this.x = 1;
   }
   write() {
      console.log(this.x);
   }
}

而巴别塔似乎转译得很好。

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

这是 ES 类字段和静态属性建议的一部分。它由 babeljs 支持,带有此插件。这是一个 babel 阶段 1 插件,所以如果你使用的是阶段 1 或阶段 0,这是支持的。

我不认为这是正确的。至少,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
   }
}

我认为单独声明成员变量没有任何价值。在构造函数中创建它。这应该是你所需要的