javascript - 类型错误 : cannot read property variable of null of a method

标签 javascript oop

我使用 JavaScript 中的 animate 方法创建了这个 class Cars。我想创建一个汽车原型(prototype)。当我尝试调用该方法时,我不断收到:

TypeError: 无法读取 'animate' 的 null 属性 'carTag'

我试图理解为什么我不断收到此错误。

class Cars{
     constructor(carTag){
    //sets up the local variables for the constructor function
         this.carTag = new Image()
         this.carTag.src = carTag
         document.getElementById("gameboard").innerHTML = 
         this.carTag
     }

     animate() {
         const image = this.carTag;
         const animate = this.animate;
         let throttle = 2000;
         const canvas = document.getElementById("gameboard");
         const ctx = canvas.getContext("2d");
         let x = canvas.width;
         let y = 0;
         setTimeout (function(){
             ctx.clearRect(0, 0, canvas.width, canvas.height);  
             ctx.drawImage(image, x, y);                    
             x -=4;
             requestAnimationFrame(animate);
       }, 1000/throttle);
    }
}

 car1 = new Cars("http://i.stack.imgur.com/Rk0DW.png");
 car1.animate();

感谢您的帮助!

更新: 错误是由 requestAnimationFrame(动画);

我想弄清楚为什么我不能通过这个循环传递图像。

感谢您的帮助。我真的很感激。

最佳答案

class Cars{
    constructor(carTag){
        //sets up the local variables for the constructor function
        this.carTag = carTag
    }
    ...
}

进行此更改,它将起作用。你的 carTagimgTag

--------------------------------编辑------------ --------------------------------

图像传递正确

首先图像已经在窗口对象中所以它已经是全局的

    
    class Cars{
        constructor(carTag){
            //sets up the local variables for the constructor function
            this.carTag = new Image()
            this.carTag.src = carTag
            document.getElementById('abcd').innerHTML = this.carTag
        }
    
        animate() {
            const image = this.carTag;
            const animate = this.animate;
            let throttle = 2000;
            setTimeout (function(){
                ctx.clearRect(0, 0, canvas.width, canvas.height);  
                ctx.drawImage(image, x, y);                    
                x -=4;
                requestAnimationFrame(animate);
          }, 1000/throttle);
        }
    }
    
    car1 = new Cars("http://i.stack.imgur.com/Rk0DW.png")

this.carTag 是一个图像对象。 希望这会有所帮助。

关于javascript - 类型错误 : cannot read property variable of null of a method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976497/

相关文章:

javascript - 多维数组和 jQuery 的 getJSON

javascript - 在 Javascript 代码中使用 Html.dropdownList()

javascript - 如何连接 2 个切片数组?

oop - 依赖/依赖是什么意思?

javascript - 摆脱多余的方法定义

c++ - 访客模式+开放/封闭原则

javascript - 我无法为 war 游戏分离卡片。它们都显示在彼此之上

java - Java 多线程、Linux 进程和 HTML5 Webworker 之间有什么区别? Webworkers的实际例子和用途是什么?

c++ - 在cpp中将对象写入文件

javascript - "this"不返回选择器