箭头函数可以在类中提升吗? javascript

问题描述

class App {
  constructor() {
    this.canvas = document.createElement('canvas');
    document.body.appendChild(this.canvas);
    this.ctx = this.canvas.getContext('2d');

    this.pixelRatio = window.devicePixelRatio > 1 ? 2 : 1;

    window.addEventListener('resize',this.resize.bind(this),false);
    this.resize();

    window.requestAnimationFrame(this.animate);
  }

  resize() {
    this.stageWidth = document.body.clientWidth;
    this.stageHeight = document.body.clientHeight;
  }

  animate = () => {
    this.test(); // ---> here!
  };

  test = () => {
    console.log('here!');
  };
}

window.onload = () => {
  new App();
};

没有提升箭头函数,只提升常规函数。怎么在animate函数里面,可以调用this.test?一个类中箭头函数的不同行为?

解决方法

虽然箭头函数没有被提升,但你在这里拥有的不是只是箭头函数——你在这里使用了类字段,它们是赋值的语法糖构造函数内部实例的值(在构造函数的开头,就在任何 super 调用之后)。您的代码相当于:

class App {
  constructor() {
    this.animate = () => {
      this.test(); // ---> here!
    };

    this.test = () => {
      console.log('here!');
    };
    this.canvas = document.createElement('canvas');
    // ...
  }
}

这不是吊装的问题。

首先 this.animate 获取分配给它的函数。然后 this.test 得到一个分配给它的函数。然后,最终,在 requestAnimationFrame 之后,调用 this.animate

一个更简单的例子:

const fn1 = () => {
  fn2();
};
const fn2 = () => {
  console.log('fn2');
};

fn1();

只要在函数被调用之前将函数分配给变量的行已经运行,一切都应该正常。