Skip to content Skip to sidebar Skip to footer

Using Es6 Arrow Functions Inside Class

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

Solution 1:

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.

Solution 2:

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.

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

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

const test1 = newStandardFunction();
const test2 = newArrowFunction();

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

I hope you find this helpful

Solution 3:

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

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

into:

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

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

Post a Comment for "Using Es6 Arrow Functions Inside Class"