You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript调用moveRight时遇Uncaught TypeError:this.bunnyImage未定义

Fixing the "this.bunnyImage is undefined" Error in Your Bunny Object

Hey there! The issue you're hitting is a common gotcha when working with constructor functions and prototypes—let's break it down and get your bunny moving properly.

What's Causing the Error?

In your drawBunny method, you create the image element as a local function variable:

var bunnyImage = document.createElement('img');

This variable only lives inside the drawBunny function, so your Bunny instance (sunflower) has no reference to it. When you try to access this.bunnyImage in moveRight, the instance doesn't have that property at all—hence the "undefined" error.

The Simple Fix

You need to attach the created image element to the Bunny instance itself, so other prototype methods can access it. Just replace the local variable with an instance property using this:

Here's the updated working code:

var Bunny = function (x, y) { this.x = x; this.y = y; }
Bunny.prototype.drawBunny = function () {
    // Assign the image to the instance instead of a local variable
    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() {
    this.x += 5;
    // Now this.bunnyImage points to the instance's attached DOM element
    this.bunnyImage.style.left = this.x + "px";
    this.bunnyImage.style.top = this.y + "px";
}

How It Works Now

When you run sunflower.drawBunny(), we create the image and store it directly on the sunflower instance via this.bunnyImage. Then, when you call sunflower.moveRight(), this.bunnyImage correctly refers to the DOM element you added to the page, letting you update its position without any errors.

Give it another test—your bunny should hop right across the screen smoothly now!

内容的提问来源于stack exchange,提问作者BlackC4t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:57:52