JavaScript调用moveRight时遇Uncaught TypeError:this.bunnyImage未定义
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

