微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更改此对象属性时出现错误“未捕获的TypeError”-JavaScript

如何解决更改此对象属性时出现错误“未捕获的TypeError”-JavaScript

我正在学习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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。