2013-02-21 90 views
1

对于下面的代码,我得到的GameStatsPanel功能的第二线以下错误:的JavaScript函数原型不能从构造的对象

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

我真的很困惑,为什么这种情况正在发生 - 我有一种感觉我错过了一些简单的地方,但我需要开悟。请随时通过访问www.letsplayglobalgames.com并选择“Play!”来查看问题。选项从主页。让我知道你是否需要更多细节。

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(); 
} 
+0

难道你创建了'新GameStatsPanel对象()' – Musa 2013-02-21 06:14:14

+0

是的,我的代码: gameStatsPanel =新GameStatsPanel(); – LetsPlayGlobalGames 2013-02-21 06:22:45

回答

3

你调用Timer构造的Timer.prototype必须设置与您的方法有机会了。

Timer函数可用,因为函数声明是“悬挂”的,因此可立即使用。

Timer.prototype的扩展不是“红旗”,让您Timer的未改进.prototype当你做new Timer

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(); 
} 

// ... 
+0

感谢您的回应,但我仍然有点困惑。在查看关于提升的更多信息之后,我理解了这个概念,但并不了解它如何应用于原型函数。你能否提供一些更多的细节或推荐一个解决问题的例子? – LetsPlayGlobalGames 2013-02-22 04:14:22

+0

@LetsPlayGlobalGames:函数声明被挂起。这意味着就好像你在文件的顶部写了Timer和GameStatsPanel函数。剩下的东西不动。因此,在上面的答案中考虑代码,想象顶部的这两个函数。然后在下面你做'gameStatsPanel = new GameStatsPanel();'。这调用'GameStatesPanel'函数,它调用'Timer',创建一个新的'Timer'实例。然后'Timer'实例调用它的'.start()'方法。麻烦的是,所有这些都发生在调用'GameStatsPanel()',这是... – 2013-02-22 04:26:17

+0

...位于* Timer.prototype.start = func ...行之前。这意味着你试图在存在之前调用'.start()'。 [此代码](http://jsfiddle.net/zQb6X/)可能有助于显示它。 '.start()'不起作用,但如果你在调用构造函数之前将它移动得更高,它就会起作用,[像这样](http://jsfiddle.net/zQb6X/2/)。 – 2013-02-22 04:27:20

相关问题