Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a javascript Object and calling it's method

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

like image 786
Danny Avatar asked Jan 14 '23 12:01

Danny


2 Answers

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;
like image 180
Pointy Avatar answered Jan 23 '23 03:01

Pointy


return x;

You never made an x variable anywhere.

You mean return this.x;.

like image 22
SLaks Avatar answered Jan 23 '23 05:01

SLaks