Reputation: 8584
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];
}
Upvotes: 0
Views: 155
Reputation: 2907
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);
}
Upvotes: 0
Reputation: 32511
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);
}
Upvotes: 2