0

New to JS and i'm having trouble figuring out how to run the constructor of newly created objects.

var player = new Player();
alert(player.getPosition()); // [ undefined, undefined ]

function Player()
{
    //afaik the x & y vars should fill when creating a new Player object.
    var x = Math.floor((Math.random() * 800) + 1), 
        y = Math.floor((Math.random() * 800) + 1);
}

Player.prototype.getPosition = function()
{
    return [this.x, this.y];
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Madmenyo
  • 8,389
  • 7
  • 52
  • 99
  • Your code does throw an `Unhandled Error: 'player.getPosition' is not a function`. See [Using prototype and dealing with execution order](http://stackoverflow.com/q/15184446/1048572) – Bergi Aug 04 '14 at 16:21
  • Local variables have nothing to do with `this`. – SLaks Aug 04 '14 at 16:23
  • @SLaks: I see now, but it's an issue that the *posted* code definitely has :-) – Bergi Aug 04 '14 at 16:24
  • For the other issue, see [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/q/13418669/1048572) – Bergi Aug 04 '14 at 16:25

2 Answers2

2

The problem is you're not assigning x and y to the instance of Player. Try this instead

function Player()
{
    this.x = Math.floor((Math.random() * 800) + 1);
    this.y = Math.floor((Math.random() * 800) + 1);
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

try this:

  function Player()
  {
//afaik the x & y vars should fill when creating a new Player object.
 this.x = Math.floor((Math.random() * 800) + 1); 
 this.y = Math.floor((Math.random() * 800) + 1);
   }
Super Hornet
  • 2,839
  • 5
  • 27
  • 55