2015-05-21 62 views
0


當我更改加載圖像後的變量,所以在gameloop我有舊值.. 我做錯了什麼?加載圖像後的類變量

var symb ; 
var Symbol=function(imgSrc) { 
    this.loaded=false; 
    this.img=new Image(); 
    this.img.onload = function() { 
     this.loaded=true; 
     console.log("in loaded - " + this.loaded); 
    } 
    this.img.src=imgSrc; 
} 
Symbol.prototype = { 
    getLoaded: function() 
    { 
     return this.loaded; 
    } 
} 

symb=new Symbol("images/worm.jpg"); 
console.log("after loaded - " + symb.getLoaded()); 
setInterval(testSymbolsLoaded, 3000); 

function testSymbolsLoaded() { 
    console.log("after 3 second loaded - " + symb.getLoaded()); 
} 

這個代碼回報

after loaded - false 
in loaded - true 
after 3 second loaded - false 

爲什麼最後一個值是假的,當早些時候變化真?

感謝您的幫助

回答

1
this.img.onload = function() { 
    this.loaded=true; 
    console.log("in loaded - " + this.loaded); 
} 

在函數,this指的是圖像的背景。你需要的功能結合到現有的this

修復:

this.img.onload = function() { 
    this.loaded=true; 
    console.log("in loaded - " + this.loaded); 
}.bind(this); 
+0

yes..it is..thanks很多 –