Using es6 arrow functions inside class

前端 未结 3 1924
孤独总比滥情好
孤独总比滥情好 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: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

提交回复
热议问题