javascript - 构造函数不工作?

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

最佳答案

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

相关文章:

php类调用外部类

c++ - 为什么类的常量数据成员需要在构造函数中初始化?

c++ - 什么是 C++ 中的就地构造函数?

c - 是否可以从目标文件中提取函数签名?

Javascript使函数一个接一个地执行

javascript - 如何重写不提供签名匹配的通用构造函数的定义

javascript - 如何将html内容添加到另一个元素?

javascript - 在 THREE.js 中使用四元数设置向量的全局旋转

javascript - 解析 - 无法从安装类中获取和更新列

javascript - 将 JSON 转换为字符串 JAVASCRIPT