开发者问题收集

更改此对象属性时出现“Uncaught TypeError”错误 - JavaScript

2020-08-19
58

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

我收到此错误:

Uncaught TypeError: this.bunnyImage is undefined

moveRight() 函数中指向 this.bunnyImage

2个回答

定义“它不起作用”(仅此声明就不足以提供帮助)。在您的情况下,控制台说:

806452921

的确, this.bunnyimage 不确定。您忘了将其存储在您的功能中, this.bunnyimage = bunnyimage;

230559721
Jeremy Thille
2020-08-19
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)
Darth
2020-08-19