3

Here is my React.js component definition:

class ExampleComponent1 extends React.Component {
    constructor() {
        super();
    }
}

When webpack this with babel loader, everything would be fine. But then I change the constructor declare to arrow function:

class ExampleComponent1 extends React.Component {
    constructor = () => {
        super();
    }
}

webpack build failed:

Module build failed: SyntaxError:....: 'super' outside of function or class (8:4)

I don't know why this happened, constructor can't declare as arrow function?

hh54188
  • 14,887
  • 32
  • 113
  • 184
  • 5
    You cannot declare *any* `class` method as an arrow function in ES6. WTH are you trying to do? An assignment inside a class body is a syntax error. – Bergi Jul 03 '16 at 10:08
  • 1
    What would you expect this transpile to? How should an arrow function (which can't be called with `new`) behave as a constructor (which can't be called without `new`)? – Bergi Jul 03 '16 at 10:13
  • in arrow function, `super` (or `this`) refers to outer lexical scope chain. unless you use arrow function in regular function, it won't work as per spec. That is the main reason you are seeing this error – Jaeho Lee Jul 03 '16 at 10:17
  • Arrow functions have no `this`, so it's not possible to use them in classes. – gcampbell Jul 03 '16 at 10:31

1 Answers1

1

In ES6, functions can be maked using arrow but only if they are procedural or lambda functions !

Into class declarations, you are only allowed to use the standard ES6 syntax :

class ExampleComponent1 extends React.Component {
    constructor() {
        super();
    }
}
ClementNerma
  • 1,079
  • 1
  • 11
  • 16