2015-02-08 36 views
0
var spaceship = { 
fps : 10, 
speed : 1, 
traveled : 0, 
currency : 0, 
initialize : function() { 
    this.update(); 
}, 
update : function() { 
    this.traveled += this.speed/this.fps; 
    setTimeout(this.update, 1000/this.fps); 
    this.render(); 
}, 
render : function() { 
    $("#spaceshipbg").attr("background-position", "0px "+this.traveled+"px"); 
} 
}; 

$(document).ready(function() { 
spaceship.initialize(); 
}); 

所以这是我的代码,每当我加载的页面中,我得到一个错误与线“this.render()”。我在这里看不到问题,我可以从初始化函数成功调用this.update(),但是当我调用this.render()时,它说它是undefined“遗漏的类型错误:未定义是不是一个函数”调用函数withing对象时

回答

1

当调用initialize时,它调用this.update()update()本身的作品,即使是第一次致电this.render()。但是,setTimeout将调用update,但它不会在您的对象上调用它。因此,this不会再引用您的对象。 this.render()未定义。

有关该问题的更多信息,请致电read this

的解决方案可能是这样的:

update : function() { 
    var self = this; 
    this.traveled += this.speed/this.fps; 
    setTimeout(function() { 
     // Enforce the correct context 
     self.update(); 
    }, 1000/this.fps); 
    this.render(); 
}, 
相关问题