5

When i change a function draw(){ //} to draw = () => { // } I am getting an error like "Uncaught SyntaxError: Unexpected token =". What may be the reason?

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
  • You will need to use babel's [Class properties transform](https://babeljs.io/docs/plugins/transform-class-properties/) – Amr Noman May 14 '18 at 08:30

3 Answers3

19

First of all, you probably shouldn't do that. Why? Well, because arrow functions are not semantically the same as regular functions.

If you register the functions as this.draw = () => {//}, then every instance of your class* will have a duplicate definition of that function which is a waste of space and a misuse of some core language features such as prototype inheritance.

draw() on the other hand registers that function on the prototype so that definition of the draw function can be shared between all instances and even changed dynamically for ALL instances at the same time.

  • 1
    This is a good answer, normally it is good to include links and blockquotes for citation, it means more people will read it – Andrew Bone May 14 '18 at 11:25
3

In your constructor you can have this.draw = () => {//} but there isn't really much point in doing this. draw(){//} should be fine for anything you want.

Below, in my example, I've shown both use cases as you can see nothing is saved by using an arrow function.

class StandardFunction {
  draw() {
    console.log('StandardFunction: you called draw')
  }
}

class ArrowFunction {
  constructor() {
    this.draw = () => {
      console.log('ArrowFunction: you called draw')
    }
  }
}

const test1 = new StandardFunction();
const test2 = new ArrowFunction();

test1.draw();
test2.draw();

I hope you find this helpful

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
1

You will need to use babel's Class properties transform, which will transpile:

class Picture {
  draw = () => {
    console.log('drawing')
  }
}

into:

class Picture {
  constructor() {
    this.draw = () => {
      console.log('drawing');
    };
  }
}

You can try it in this repl (make sure to enable the class properties transform plugin)

Amr Noman
  • 2,597
  • 13
  • 24