Ben Grandin
Ben Grandin

Reputation: 176

Javascript class: What's the difference between public fields and fields

In a JS class what's the difference between:

class MyClass extends components {
    constructor(props) {
        super(props);
        this.state = {toto:"toto"}
    }
}

and

class MyClass extends components {
    state = {toto:"toto"}
}

[Edit] It's the same: Thanks for your answers !

Upvotes: 1

Views: 298

Answers (2)

Travis James
Travis James

Reputation: 1939

Declaring state like this without a constructor:

state = {}

Is called class fields, TC39 proposal currently on stage 3 last I checked, but it has wide spread adoption in the React community.

Basically it isn't currently part of javascript, but compilers such as babel allow this syntax and will compile it into valid javascript code.

Upvotes: 2

Daijoubu
Daijoubu

Reputation: 44

No difference, its just a syntactic sugar

Upvotes: 1

Related Questions