JavaScript原型函数在构造的对象中不可用

JavaScript原型函数在构造的对象中不可用,javascript,oop,prototypejs,Javascript,Oop,Prototypejs,对于下面的代码,我在GameStatsPanel函数的第二行得到以下错误: “未捕获类型错误:对象#计时器没有方法‘启动’” 我真的很困惑为什么会发生这种情况——我有一种感觉,我在某个地方错过了一些简单的东西,但我需要启发。请访问www.letsplayglobalgames.com并选择“播放”,查看该问题选择从主页。如果你需要更多的细节,请告诉我 function GameStatsPanel() { this.timer = new Timer(); this.timer.

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

“未捕获类型错误:对象#计时器没有方法‘启动’”

我真的很困惑为什么会发生这种情况——我有一种感觉,我在某个地方错过了一些简单的东西,但我需要启发。请访问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
的扩展没有被“提升”,因此当您执行
新定时器时,您的
定时器
有一个未修改的
.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();
}

// ...

您是否创建了类似于
newgamestatspanel()
的对象是的,我有代码:GameStatsPanel=newgamestatspanel();谢谢你的回复,但我还是有点困惑。在查看了一些关于提升的更多信息后,我理解了这个概念,但没有理解它是如何应用于原型功能的。你能提供更多的细节或推荐一个例子来解决这个问题吗?@LetsPlayGlobalGames:函数声明被提升了。这意味着好像您在文件顶部编写了
计时器
游戏状态面板
函数。其余的东西都不动了。以我上面答案中的代码为例,想象一下上面的两个函数。然后在下面执行
gameStatsPanel=newgamestatspanel()。这将调用
GameStatesPanel
函数,该函数调用
Timer
,创建一个新的
Timer
实例。
计时器
实例然后调用其
.start()
方法。问题是,所有这些都是在调用
GameStatsPanel()
时发生的,该面板位于
Timer.prototype.start=func…
行之前。这意味着您试图在它存在之前调用
.start()
。也许有助于展示它。
.start()
不起作用,但是如果在调用构造函数之前将其向上移动,它就会起作用,….基本上,确保在完全设置函数之前不会调用任何函数。啊,知道了。但我不确定我是否喜欢。。。让我想起了C代码,其中文件中函数的顺序/位置很重要。感谢您的回复,感谢您花时间将代码放入JSFIDLE。非常感谢!