【问题标题】:can arrow function gets hoisted in a class? (javascript)箭头函数可以在课堂上提升吗? (javascript)
【发布时间】:2020-12-30 17:34:24
【问题描述】:

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?类中箭头函数的不同行为?

【问题讨论】:

    标签: javascript hoisting


    【解决方案1】:

    虽然没有提升箭头函数,但您在此处拥有的并不是 只是 箭头函数 - 您在这里使用的是 类字段,它们是用于分配的语法糖构造函数内部实例的值(在构造函数的开头,就在任何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();

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

    【讨论】:

    • ``` videoElem.addEventListener('canplaythrough', render);常量渲染 = () => { ctx.drawImage(videoElem, 0, 0, 600, 400); ctx.font = '20px 蹦极轮廓'; ctx.fillStyle = '白色'; } ``` 在这种情况下,我得到了一个错误 - 那为什么会这样呢?
    • @facVV 因为,正如CertainPerformance 解释的那样,箭头函数没有被提升(在你的意思上),你在课堂上看到的是另一回事。然而,这个例子中根本没有类,所以即使它们看起来相似,它们也是不同的。这个例子可以参考TDZ (Temporal Dead Zone)
    • @CertainPerformance 如果我是对的,那么 facVV 注释中代码的问题是 render 变量(包含箭头函数)的引用早于它的定义......
    • @facVV 在初始化行(带有const someVarName =)的行运行之前,您不能运行引用变量的行。
    猜你喜欢
    • 2022-11-22
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多