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

6

对于下面的代码,我想了解 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;
   }
} 

变量和属性不同。因此,如果类字段的语法使用varletconst,只会让人感到困惑。 - Felix Kling
2个回答

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";         
}

实际上,目前这两者都不是合法的JavaScript。后者是类字段的一个示例,它目前是一个stage 3 proposal,因此它最终将成为合法语法。使用转译器,您可以立即使用该语法,而转译器将把代码移动到构造函数中。

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

成为大致如下:

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

2
这段话的意思是:“平凡的答案是‘因为(目前)class 语法就是这样定义的。’ 类声明基本上是一堆简写的函数声明(它们只是省略了“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 - 私有成员解释?),但我认为它偏离了类语法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接