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
Canvas
5,9159 gold badges60 silver badges103 bronze badges
2 Answers 2
You can;
Hero.prototype.MoveHero = function( xSpeed, ySpeed )
{
this.xPos += xSpeed;
this.yPos += ySpeed;
}
answered Jan 21, 2014 at 14:30
Alex K.
177k32 gold badges276 silver badges299 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
function Hero()
{
// add other properties
this.MoveHero = function( xSpeed, ySpeed )
{
this.xPos += xSpeed;
this.yPos += ySpeed;
}
}
answered Jan 21, 2014 at 14:33
Rami Enbashi
3,5561 gold badge21 silver badges21 bronze badges
Comments
default
Hero.prototype.MoveHero=function(....)