为什么在 ES6 JavaScript 中调用 class 时得到的值为 null?

Why do I get value of null when calling a class in ES6 JavaScript?

编辑:这个问题和答案比另一个说 'duplicate' 的答案要好得多,也更有意义。值得保留以供进一步参考,而且这对初学者很友好,因为我不知道 callbacl 是什么以及 foo boo bar 的所有令人困惑的示例...

在另一个 class 的方法中调用 class 时,我得到的值为 null。我想为 JavaScript canvas 中的对象设置动画。

我正在用 JavaScrpt canvas 制作一个小动画,我也在学习 classes 和 JavaScript 的一般知识。所以一个新手问题。

如何消除错误并使其正常工作?

这是代码笔:https://codepen.io/Aurelian/pen/mGWVbq?editors=0010

这是JS:

'use strict';
function random(min, max) {
  return Math.random() * (max - min) + min;
}
   /*
    * ------------------------------------------
    * *-----------------------------
    *  User Event
    * *-----------------------------
    * ------------------------------------------
    */
   class UserEvent {
      constructor(canvasBody) {
         this.UP_ARROW = 38 || 87,
         this.RIGHT_ARROW =39 || 68,
         this.DOWN_ARROW = 37 || 83,
         this.LEFT_ARROW = 40 || 65,
         this.keys = []

         canvasBody.addEventListener('keydown', (e) => {
            this.keys[e.keyCode] = true;
         });

         canvasBody.addEventListener('keyup', (e) => {
            this.keys[e.keyCode] = false;
         });
      }

      checkKey(key) {
         return this.keys[key];
      }

//       ufoMove() {
//          this.canvasBody.checkKey(this.UP_ARROW)
//          this.canvasBody.checkKey(this.RIGHT_ARROW)
//          this.canvasBodycheckKey(this.DOWN_ARROW)
//          this.canvasBody.checkKey(this.LEFT_ARROW)
//          console.log(this.canvasBody.leftArrow = this.checkKey(this.LEFT_ARROW))

//          if(this.UP_ARROW) {
//             this.x += this.x * this.velocity.x
//          }
//       }
   }


   /*
    * ------------------------------------------
    * *-----------------------------
    *  UFO
    * *-----------------------------
    * ------------------------------------------
    */
   class Ufo {
      constructor(x, y) {
         this.x = x,
         this.y = y,
         this.velocity = {
            x: 3,
            y: 3
         }
      }

      draw(c) {
         c.save()
         c.beginPath()
         c.arc(this.x, this.y, 50, 0, Math.PI * 2, false)
         c.fillStyle = "#fff";
         c.shadowColor = "#e3eaef";
         c.shadowBlur = 20;
         c.fill()
         c.closePath()
         c.restore()
      }

      update(c) {
         this.draw(c)
         // Get the keys first
         // this.EventUser.ufoMove(c);
         this.x = this.x + random(-5,5);
         this.y = this.y + random(-5,5);
         //    this.x = this.x + this.velocity.x;
         // }
      }
   }

   /*
    * ------------------------------------------
    * *-----------------------------
    *  Canvas
    * *-----------------------------
    * ------------------------------------------
    */      
   class CanvasDisplay {
      constructor() {
         this.canvas = document.querySelector('canvas');
           this.ctx = this.canvas.getContext('2d');
         this.stageConfig = {
              width: window.innerWidth,
              height: window.innerHeight
         };         
         this.canvas.width = this.stageConfig.width;
         this.canvas.height = this.stageConfig.height;

         this.backgroundGradient = this.ctx.createLinearGradient(0, 0, 0, this.canvas.height);
         this.backgroundGradient.addColorStop(0, '#171e26');
         this.backgroundGradient.addColorStop(1, '#3f586b');

         this.Ufo = new Ufo(this.canvas.width / 2, this.canvas.height / 2);
         this.UserEvent = new UserEvent(document.body);
      }

      animate() {
         this.ctx.fillStyle = this.backgroundGradient;
         this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

         this.Ufo.update(this.ctx)
         window.requestAnimationFrame(this.animate);
      }
   }

   let canvasDisplay = new CanvasDisplay();
   canvasDisplay.animate();

问题是

window.requestAnimationFrame(this.animate);

当您将函数作为回调传递时,它不会保留正常调用时的调用上下文,例如,this.animate(),它的调用上下文为 this.就像

function runCallback(callback) {
  callback();
}

默认情况下 运行 callback 没有调用上下文。

所以,在animate中,当第一行是

this.ctx.fillStyle = ...

发生错误,因为this没有引用实例化对象,当animate由于requestAnimationFrame.

被调用时

相反,当您将 this.animate 传递给 requestAnimationFrame 时,显式 将调用上下文绑定 this

window.requestAnimationFrame(this.animate.bind(this));

或传递 调用 this.animate():

的函数
window.requestAnimationFrame(() => this.animate());

您必须在以下位置绑定范围:

window.requestAnimationFrame(this.animate.bind(this));

因为匿名函数不会自行绑定它。

编辑:没有看到@CertainPerformance 的回答。