Declaring an es6 function in a React class

What is the difference between functions declared with const and functions declared without let or const and a function declared differently in ES6 class?

class App extends Component {

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

Why the above works fine, but the declaration below gives an error:

class App extends Component {

    const submitFood = () =>{
        // some code
        }
+4
source share
2 answers

First of all: none of the examples you cited are valid ES6. Grammar rules for ES6 classes allow you to allow method definitions within the class body. I.e.

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

The first example, however, uses the suggestion of class field suggestions . This sentence extends the existing grammar by defining form properties.

class MyClass {
  someProperty = value;
}

, . :

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

- , let const .

, .

+2

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

(submitFood=() {}) , let const.
, submitFood() . ( ReferenceError).

-2

Source: https://habr.com/ru/post/1688232/


All Articles