Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

hoisting - can arrow function gets hoisted in a class? (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();
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although arrow functions aren't hoisted, what you have here aren't just arrow functions - you're using class fields here, which are syntax sugar for assigning a value to the instance inside the constructor (at the beginning of the constructor, just after any super calls). Your code is equivalent to:

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

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

It's not an issue of hoisting.

First this.animate gets a function assigned to it. Then this.test gets a function assigned to it. Then, eventually, after a requestAnimationFrame, this.animate is called.

For a more minimal example of this:

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

fn1();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...