Javascript 类型错误:无法读取方法的null属性变量
我使用JavaScript中的方法Javascript 类型错误:无法读取方法的null属性变量,javascript,oop,Javascript,Oop,我使用JavaScript中的方法animate创建了这个类Cars。我想创建一个汽车原型。当我尝试调用该方法时,我不断得到: TypeError:无法读取'animate'的null属性'carTag'。 我正在努力理解为什么我总是犯这个错误 class Cars{ constructor(carTag){ //sets up the local variables for the constructor function this.carTag = new
animate
创建了这个类Cars
。我想创建一个汽车原型。当我尝试调用该方法时,我不断得到:
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();
谢谢你的帮助
更新:
错误是由以下原因引起的:
请求动画帧(动画)
我试图弄明白为什么我不能通过这个循环传递图像
谢谢你的帮助。我真的很感激。在animate函数中,这指的是animate函数本身,而不是它所属的对象。在类定义中,可以说“var self=this;”,并在animate函数中使用self.carTag。但是,在动画的定义中使用self.animate可能仍然存在问题
class Cars{
constructor(carTag){
//sets up the local variables for the constructor function
this.carTag = carTag
}
...
}
做出这个改变,它就会起作用。您的carTag是imgTag
----------------------------------编辑-------------------------------------------
图像传递正确吗
首先,图像已经在窗口对象中,所以它已经是全局的
高级轿车{
建造商(carTag){
//为构造函数设置局部变量
this.carTag=新图像()
this.carTag.src=carTag
document.getElementById('abcd')。innerHTML=this.carTag
}
制作动画(){
const image=this.carTag;
const animate=this.animate;
设节流阀=2000;
setTimeout(函数(){
clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(图像,x,y);
x-=4;
请求动画帧(动画);
},1000/节);
}
}
car1=新车(“http://i.stack.imgur.com/Rk0DW.png)
你有没有可能发布整个课程?谢谢。你是不是先实例化(创建/初始化)了一个对象?如果不是,它将是空的,并且将没有任何内容可阅读。当发布您的类时,这应该更容易理解,并且我们可以确切地看到正在发生的事情。:)我认为如果一个函数在一个类中,它就叫做一个方法。我希望这有助于更好地理解这个问题。我很困惑为什么会收到错误消息。即使imgTag引用了新映像()。我尝试过这样做,然后得到以下结果:未捕获类型错误:未能在“CanvasRenderingContext2D”上执行“drawImage”:提供的值不是类型(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HtmlCanvaElement或ImageBitmap或OffscreenCanvas)'您通过构造函数传递的是carTag,但您分配的是self.carTag=imgTag,而不是self.carTag=carTagI,因此会收到相同的错误消息。谢谢你。我真的很感激。构造器是正确的,它必须是正确的。尽管你是对的,但还是要做动画。构造函数是正确的。我发现了真正的问题:requestAnimationFrame给了我:TypeError:无法读取“animate”null的属性“carTag”。