刚接触 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];
}
最佳答案
问题是您没有将 x
和 y
分配给 Player
的实例。试试这个吧
function Player()
{
this.x = Math.floor((Math.random() * 800) + 1);
this.y = Math.floor((Math.random() * 800) + 1);
}
关于javascript - 构造函数不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123158/