3

Hello there stackoverflow people, I'm messing around with HTML5 and Javascript and I'm trying to add a function to an object in javascript, just like a function is added to a class in C#. Here is my javascript (I know this doesn't work)

function Hero()
{
 this.xPos = 100;
 this.yPos = 100;
 this.image = new Image();
 this.image.src = "Images/Hero.png";
}
function MoveHero( xSpeed, ySpeed )
{
 xPos += xSpeed;
 yPos += ySpeed;
}

Now in my main loop function like so

function main()
{
 canvas.fillStyle = "#555555";
 canvas.fillRect( 0, 0, 500, 500);
 canvas.drawImage( hero.image, hero.xPos, hero.yPos );
 hero.MoveHero(1,1);
}

Now this ofcourse tells me that

"Uncaught TypeError: Object #<Hero> has no method 'MoveHero'"

How would I link the function so I could use

hero.MoveHero(x,y);

If anyone could help me out it would be awesome.

P.S. I am declaring my hero variable globally like so

var hero = new Hero();

is that ok?

asked Jan 21, 2014 at 14:27
1
  • Hero.prototype.MoveHero=function(....) Commented Jan 21, 2014 at 14:29

2 Answers 2

10

You can;

Hero.prototype.MoveHero = function( xSpeed, ySpeed )
{
 this.xPos += xSpeed;
 this.yPos += ySpeed;
}
answered Jan 21, 2014 at 14:30
Sign up to request clarification or add additional context in comments.

Comments

1
function Hero()
{
 // add other properties
 this.MoveHero = function( xSpeed, ySpeed )
 {
 this.xPos += xSpeed;
 this.yPos += ySpeed;
 }
}
answered Jan 21, 2014 at 14:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.