Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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
        }
like image 362
jojojohn Avatar asked Oct 26 '17 15:10

jojojohn


People also ask

How do I declare a function in ES6?

Let us first understand what exactly the function is and how to declare a function in ES6 using different syntaxes. function display(name) { console. log(name) } display("Geeksforgeeks"); let display = name = console. log(name); display("Geeksforgeeks");

What is ES6 class in React?

ES6 introduced classes. A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class , and the properties are assigned inside a constructor() method.

What does => in React mean?

The () => { ... } is the function. It's an ES6-style "arrow" function expression. These are like function expressions ( tick = function() { ... } ) except that the this value within the function is inherited from the context in which it's defined rather than being set when the function is called.


1 Answers

First of all: None of the examples you provided is valid ES6. The grammar rules for ES6 classes only allow methods definitions inside the class body. I.e.

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.

Keep in mind that class fields are not variable declarations or variable assignments.

like image 122
Felix Kling Avatar answered Oct 26 '22 17:10

Felix Kling