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

问题描述 投票:0回答:2

对于以下代码,我想知道在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;
   }
} 
javascript reactjs class ecmascript-6 es6-class
2个回答
1
投票
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,因此最终将成为合法语法。使用transpiler,您可以立即使用该语法,编译器会将代码移入构造函数。

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

大致成为:

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

0
投票

简单的答案是“因为(当前)定义了class语法”。

类声明基本上是一堆速记函数声明(它们只是删除了“ function”关键字),您不能将可执行语句放在方法之外(建议的public and private fields除外,但是它们不在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 - Private members explanation?),但我认为它与类语法不符。

© www.soinside.com 2019 - 2024. All rights reserved.