0

First I write the code below in development tool, and all work fine:

class MyClass {
  constructor(name, verb, noun) {
     this.name = name;
     this.verb = verb;
     this.noun = noun;
  }

  myFunc() {
    return `${this.name}${this.verb}${this.noun}`
  }
}

But, if I change it to:

class MyClass {
  constructor(name, verb, noun) {
     this.name = name;
     this.verb = verb;
     this.noun = noun;
  }

  myFunc = () => {
    return `${this.name}${this.verb}${this.noun}`
  }
}

just transferring traditional function to arrow function, it will tell me:

Uncaught SyntaxError: Unexpected token =

Can't I write arrow function in class?

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
  • No, you can't. That's invalid syntax. – Patrick Roberts Dec 16 '18 at 09:42
  • @PatrickRoberts - It'll be valid fairly soon, it's [at Stage 3](https://github.com/tc39/proposal-class-fields) and is commonly transpiled. But @ WreewanMorhee, it's generally not a good idea. Better to `bind` in the constructor. See [this](https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1) and [this](https://github.com/tc39/proposal-decorators/blob/master/bound-decorator-rationale.md). – T.J. Crowder Dec 16 '18 at 09:47
  • @T.J.Crowder okay, fine. It's invalid syntax **according to the current standard specification**, and not the ESnext specification. – Patrick Roberts Dec 16 '18 at 09:51

0 Answers0