构造函数不工作?

时间:2014-08-04 16:19:13

标签: javascript function constructor

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];
}

2 个答案:

答案 0 :(得分:2)

问题是您没有将xy分配给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);
   }