javascript - 为什么在 ES6 JavaScript 中调用类时得到 null 值?

标签 javascript ecmascript-6 html5-canvas es6-class

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

当在另一个类的方法中调用一个类时,我得到一个 null 值。我想在 JavaScript Canvas 中为对象添加动画效果。

我正在使用 JavaScrpt Canvas 制作一个小动画,并且我还在学习一般的类和 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(),它将具有调用上下文这个。就像

function runCallback(callback) {
  callback();
}

默认情况下,它将在没有调用上下文的情况下运行回调

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

this.ctx.fillStyle = ...

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

相反,当您将 this.animate 传递给 requestAnimationFrame 时,可以将调用上下文显式绑定(bind)this:

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

或传递一个调用的函数this.animate():

window.requestAnimationFrame(() => this.animate());

关于javascript - 为什么在 ES6 JavaScript 中调用类时得到 null 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52140743/

相关文章:

javascript - (this) 在函数声明之后

破折号分隔并以年份开头时的 Javascript Date.parse 错误

javascript - 为什么在 ES6 中不能命名常量 fetch

javascript - Rx (RxJS) 网址生成器

jquery - HTML + JS 与 HTML5 性能对比

python - 如何按主色自动分类图像?

javascript - Material UI - 提供给 ButtonBase 的 `component` Prop 无效。请确保 children Prop 在此自定义组件中呈现

Javascript 函数 - 可能有什么问题?

javascript - react : Search Filter is not working Properly

javascript - 在HTML5 Canvas 上慢慢绘制二次曲线