简体   繁体   English

React类中的es6函数声明

[英]es6 function declaration in React class

Whats the difference between functions declared with const and functions declared without let or const and a function declared otherwise in an ES6 class? 什么是用const声明的函数和没有let或const声明的函数和在ES6类中声明的函数之间的区别?

class App extends Component {

    submitFood = () =>{
        // some code
    }

Why does the above work OK but the declaration below give an error: 为什么上面的工作正常,但下面的声明给出了错误:

class App extends Component {

    const submitFood = () =>{
        // some code
        }

First of all: None of the examples you provided is valid ES6. 首先:您提供的示例都不是有效的ES6。 The grammar rules for ES6 classes only allow methods definitions inside the class body. ES6类的语法规则仅允许类主体内的方法定义 Ie

class MyClass {
  method1() {}
  method2() {}
}

The first example however is making use of the class fields proposal . 然而,第一个例子是使用类字段提案 This proposal extends the existing grammar to allow the definition of properties of the form 该提议扩展了现有语法,以允许定义表单的属性

class MyClass {
  someProperty = value;
}

These assignments are not evaluated at class definition time but at instantiation time. 这些赋值不会在类定义时评估,而是在实例化时评估。 It's syntactic sugar for assigning properties in the constructor: 它是在构造函数中分配属性的语法糖:

class MyClass {
  constructor() {
    this.someProperty = value;
  }
}

Your second example is simply invalid syntax because there are no grammar rules that allow putting let or const before the class field. 你的第二个例子只是无效的语法,因为没有语法规则允许在类字段之前放置letconst

Keep in mind that class fields are not variable declarations or variable assignments. 请记住,类字段不是变量声明或变量赋值。

const submitFood = () =>{ // some code }

Is the creation of function (submitFood=() {}) and the creation of a variable so usual rules in variable hosting blocked let and const . 是创建函数(submitFood=() {})和变量的创建所以通常的规则在变量托管中阻塞了letconst
so fail since submitFood() is not defined. 所以失败,因为没有定义submitFood() (It will throw a ReferenceError). (它会抛出一个ReferenceError)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM