Reputation: 5897
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?
Upvotes: 3
Views: 231
Reputation: 3556
function Hero()
{
// add other properties
this.MoveHero = function( xSpeed, ySpeed )
{
this.xPos += xSpeed;
this.yPos += ySpeed;
}
}
Upvotes: 1
Reputation: 175826
You can;
Hero.prototype.MoveHero = function( xSpeed, ySpeed )
{
this.xPos += xSpeed;
this.yPos += ySpeed;
}
Upvotes: 10