JS的新手,我无法弄清楚如何运行新创建的对象的构造函数。
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];
}
答案 0 :(得分:2)
问题是您没有将x
和y
分配给Player
的实例。试试这个
function Player()
{
this.x = Math.floor((Math.random() * 800) + 1);
this.y = Math.floor((Math.random() * 800) + 1);
}
答案 1 :(得分:0)
试试这个:
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);
}