Using es6 arrow functions inside class

前端 未结 3 1837
孤独总比滥情好
孤独总比滥情好 2020-12-10 20:57

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

相关标签:
3条回答
  • 2020-12-10 21:40

    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)

    0 讨论(0)
  • 2020-12-10 21:44

    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.

    0 讨论(0)
  • 2020-12-10 21:51

    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

    0 讨论(0)
提交回复
热议问题