简体   繁体   English

Javascript“对象没有方法”错误

[英]Javascript 'object has no method' error

This seems to be a popular question on this site but previous answers haven't solved this instance of the problem. 这似乎是该网站上的一个热门问题,但是以前的答案尚未解决此问题的实例。

I have the beginnings of a game engine on a node.js server but when I set it going I get the following error occuring in the loop method: Object #<Timer> has no method update . 我有一个在node.js服务器上的游戏引擎的开始,但是当我将其设置为运行时,我在loop方法中遇到以下错误: Object #<Timer> has no method update

I thought I was setting the prototype to have an update method with GameEngine.prototype.update = function(){ ... }; 我以为我将原型设置为使用GameEngine.prototype.update = function(){ ... };

Any help in solving this problem would be much appreciated. 解决该问题的任何帮助将不胜感激。 Thank you. 谢谢。

Here's the entire code: 这是整个代码:

function GameEngine(){
    this.fps = 1000/60;
    this.deltaTime = 0;
    this.lastUpdateTime = 0;
    this.entities = [];
}

GameEngine.prototype.update = function(){
    for(var x in this.entities){
        this.entities[x].update();
    }
}

GameEngine.prototype.loop = function(){
    var now = Date.now();
    this.deltaTime = now - this.lastUpdateTime;
    this.update();
    this.lastUpdateTime = now;
}

GameEngine.prototype.start = function(){
    setInterval(this.loop, this.fps);
}

GameEngine.prototype.addEntity = function(entity){
    this.entities.push(entity);
}

var game = new GameEngine();
game.start();

This seems to be a popular question on this site 这似乎是该网站上的一个热门问题

Yes. 是。

but previous answers haven't solved this instance of the problem. 但先前的答案尚未解决此问题的实例。

really? 真? Which ones have you found? 您找到了哪些?


The context of the "method" ( this ) is lost when the function is executed by a timeout/event listener/etc. 函数由超时/事件监听器/等执行时,“方法”( this )的上下文丢失。

GameEngine.prototype.start = function(){
    var that = this;
    setInterval(function(){
       that.loop();
    }, this.fps);
}

or 要么

GameEngine.prototype.start = function(){
    setInterval(this.loop.bind(this), this.fps);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM