Creating a javascript object and calling its method

I have the following code in a single file, but it does not seem to work.

I basically try to create an object and try to just call the function of the object and display it, it does not, and I do not 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 trying to get this job would be greatly appreciated.

thanks

+4
source share
3 answers

In your "moving" functions, you must consistently reference this.x :

  this.x = this.x - 1; 

Similarly, the getXPos function should also be:

  return this.x; 
+5
source
 return x; 

You have never changed the variable x .

You mean return this.x; .

+3
source

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

+1
source

All Articles