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?

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;
}
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;
    }
}

Comments

Your Answer

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.