对于下面的代码,我在 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/