4

I have the following code, in one file, but it doesnt seem to work.

I'm basically trying to create an object and try to simply call the object's function and display it, it doesn't do that and I dont know why.

var mice = new Mice(10, 10);
function Mice(posX, posY)
{
    this.x = posX;
    this.y = posY;
    this.moveLeft = function ()
    {
        this.x = x - 1;
    }

    this.moveRight = function ()
    {
        this.x = x + 1;
    }

    this.getXPos = function ()
    {
        return this.x;
    }
}

document.onkeydown = function(e)
{
    //document.getElementById("mainBody").innerHTML = e.keyCode;

    switch(e.keyCode)
    {
    case 37:
        //document.getElementById("mainBody").innerHTML = "you have pressed left";
        mice.moveLeft();
        document.getElementById("mainBody").innerHTML = mice.getXPos();
        break;
        default:
    //do nothing
    break;
    }
}

any help on trying to get this working will be greatly appreciated.

Thanks

3 Answers 3

5

In your "move" functions, you have to consistently refer to this.x:

    this.x = this.x - 1;

Similarly, the "getXPos" function must also:

    return this.x;
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for mentioning the need to do this (no pun intended) consistently. And for giving examples as to how this should look in the other functions, as well as getXPos().
3
return x;

You never made an x variable anywhere.

You mean return this.x;.

2 Comments

Many thanks for point the error out. However, I've corrected it and it still doesn't work...
@Danny You'll also need to do this.x = this.x - 1; (or just this.x -= 1;) and this.x = this.x + 1;.
1

There is no x variable in the scope of your getXPos() method. I think you mean to return this.x

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.