2015-02-08 72 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(); 
}, 
相關問題