问题描述
我正在学习JavaScript中的对象和原型,但被困住了。 我的目的是创建一个对象,然后将其绘制到页面上。我创建了另一个原型构造函数,因此稍后可以将这个特定创建的对象移动到页面上,但是它不起作用,而且我不知道如何继续使用它
这是我的JS:
var Bunny = function (x,y) {
this.x = x;
this.y = y;
}
Bunny.prototype.drawBunny = function () {
var bunnyImage = document.createElement('img');
bunnyImage.src = "https://64.media.tumblr.com/tumblr_m06yweMXBl1qaajuxo1_500.gif";
bunnyImage.style.position = "absolute";
bunnyImage.style.left = this.x + "px";
bunnyImage.style.top = this.y + "px";
document.getElementsByTagName("body")[0].appendChild(bunnyImage);
}
Bunny.prototype.moveRight = function() {
this.x += 5;
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
}
,然后在控制台日志中(这有效):
var sunflower = new Bunny(200,200);
sunflower.drawBunny();
但是当我在控制台日志中写这个时:
sunflower.moveRight();
我收到此错误:
未捕获的TypeError:this.bunnyImage未定义
指向this.bunnyImage
函数中的moveRight()
解决方法
var Bunny = function (x,y) {
this.x = x;
this.y = y;
}
Bunny.prototype.drawBunny = function () {
this.bunnyImage = document.createElement('img');
this.bunnyImage.src = "https://64.media.tumblr.com/tumblr_m06yweMXBl1qaajuxo1_500.gif";
this.bunnyImage.style.position = "absolute";
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
document.getElementsByTagName("body")[0].appendChild(this.bunnyImage);
}
Bunny.prototype.moveRight = function(delta = 5) {
this.x += delta;
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
}
var sunflower = new Bunny(200,0);
sunflower.drawBunny();
// Lets dance
setInterval(() => {
sunflower.moveRight(200 * (.5 - Math.random()))
},200)
,
定义“它不起作用”(仅此语句不足以提供帮助)。在您的情况下,控制台会显示:
未捕获的TypeError:无法读取未定义的属性'style'
实际上,this.bunnyImage
未定义。您忘记了使用this.bunnyImage = bunnyImage;
var Bunny = function(x,y) {
this.x = x;
this.y = y;
}
Bunny.prototype.drawBunny = function() {
var bunnyImage = document.createElement('img');
bunnyImage.src = "https://64.media.tumblr.com/tumblr_m06yweMXBl1qaajuxo1_500.gif";
bunnyImage.style.position = "absolute";
bunnyImage.style.left = this.x + "px";
bunnyImage.style.top = this.y + "px";
this.bunnyImage = bunnyImage;
document.getElementsByTagName("body")[0].appendChild(bunnyImage);
}
Bunny.prototype.moveRight = function() {
this.x += 5;
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
}
var sunflower = new Bunny(200,200);
sunflower.drawBunny();
sunflower.moveRight();