为什么我不能在 ES6 类中使用 let、const 或 var 关键字声明变量,但我可以直接声明它?

IT技术 javascript reactjs class ecmascript-6 es6-class
2021-05-03 02:15:59

对于以下代码,我想知道 ES6 类中这种行为背后的原因:

class One {
    //why the following code is not allowed.
    let check = false; 
    const PI = 3.14;   
    var v = 'Hello';    

    //why the following code is allowed.
    chk = false;       
    Pi = 3.14;         
    vv = "Hi";         
}

我知道我可以编写如下代码,但我想知道上述代码背后的真正原因。

class Sample {
   constructor(x, y) {
      this.x= x;
      this.y= y;
   }
} 
2个回答
class One {
    //why the following code is not allowed.
    let check = false; 
    const PI = 3.14;   
    var v = 'Hello';    

    //why the following code is allowed.
    chk = false;       
    Pi = 3.14;         
    vv = "Hi";         
}

实际上,目前这些都不是合法的 javascript。后者是类字段的示例,目前是第 3 阶段的提案,因此最终会成为合法的语法。使用transpiler,您现在可以使用该语法,transpiler 会将代码移动到构造函数中。

class One {
  chk = false;       
  Pi = 3.14;         
  vv = "Hi";         
}

大致变成:

class One {
  constructor() {
    this.chk = false;       
    this.Pi = 3.14;         
    this.vv = "Hi";         
  }
}

简单的答案是“因为这就是(当前)定义语法的方式”。

类声明基本上是一堆速记函数声明(它们只是去掉了“function”关键字),您不能将可执行语句放在方法之外(建议的公共和私有字段除外,但它们不在 ECMA-262 中)还)例如

class Foo {

  // shorthand function declaration of mandatory constructor method
  constructor (...) {
    // Usual function syntax in here
  }

  // shorthand function declaration of class method
  blah (...) {
    // Usual function syntax in here
  }

  // shorthand function declaration of static method
  static bar (...) {  
    // Usual function syntax in here
  }

  // etc.
}

有一些方法可以实现私有成员(JavaScript - 私有成员解释?),但我认为它脱离了类语法。