JavaScript 原型(prototype)函数在构造对象中不可用

标签 javascript oop prototypejs

对于下面的代码,我在 GameStatsPanel 函数的第二行收到以下错误:

"Uncaught TypeError: Object #Timer has no method 'start'"

我真的很困惑为什么会这样——我觉得我在某处遗漏了一些简单的东西,但我需要启发。请随时访问 www.letsplayglobalgames.com 并选择“播放!”来检查问题。从主页选项。如果您需要更多详细信息,请告诉我。

function GameStatsPanel() {
    this.timer = new Timer();
    this.timer.start(); /* error is thrown here */
}
function Timer() {
    this.container = document.getElementById('game_time');
    this.current_flag_time_start;
    this.current_flag_time_stop;
    this.time_start = new Date();
    this.time_stop;
    this.time_difference;
    this.current_flag_time_difference;
}
Timer.prototype.start = function() {
    this.current_flag_time_start = new Date();
}

最佳答案

Timer.prototype 有机会使用您的方法设置之前,您正在调用 Timer 构造函数。

Timer 函数可用,因为函数声明被“提升”,因此立即可用。

Timer.prototype 的扩展没有被“提升”,所以当您执行 时,您的 Timer 有一个未修改的 .prototype新计时器

gameStatsPanel = new GameStatsPanel(); // Invoking this too soon. Put it and
// ...                            // anything else that uses the constructors at
                                  // the bottom so the prototypes can be set up.
function main() {
   // ...
}

function GameStatsPanel() {
    this.timer = new Timer(); // The `Timer.prototype` extensions haven't run yet
    // ...
    this.timer.start(); // .start doesn't yet exist
}

// ...

function Timer() {
    // ...
}

// ...

 // *Now* the .start() method is getting added.
Timer.prototype.start = function () {
    this.current_flag_time_start = new Date();
}

// ...

关于JavaScript 原型(prototype)函数在构造对象中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995694/

相关文章:

javascript - 如何使用 ionic 和 firebase 获取注册用户的 uid

php - 我们应该或不应该在模型中使用参数吗?

javascript - 如何一次显示所有回调结果(格式化)

javascript - 通过触发器实例化 Backbone? (或者如何推迟匿名函数的执行?)

php - 关系数据库中的面向对象结构

oop - 我如何用看似无目标的想法构建面向对象的软件?

javascript - 如何通过原型(prototype) Ajax.Request() 传递 HTTP AUTH 值?

Javascript 下拉菜单小部件

javascript - JS Prototype 在点击时替换图片 url

Javascript点击功能问题