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

yog*_*dra 6 javascript class ecmascript-6 reactjs es6-class

对于以下代码,我想知道 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";         
}
Run Code Online (Sandbox Code Playgroud)

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

class Sample {
   constructor(x, y) {
      this.x= x;
      this.y= y;
   }
} 
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 4

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";         
}
Run Code Online (Sandbox Code Playgroud)

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

class One {
  chk = false;       
  Pi = 3.14;         
  vv = "Hi";         
}
Run Code Online (Sandbox Code Playgroud)

大致变成:

class One {
  constructor() {
    this.chk = false;       
    this.Pi = 3.14;         
    this.vv = "Hi";         
  }
}
Run Code Online (Sandbox Code Playgroud)