class 加载图像后变量

class variable after load image


当我在加载图像后更改变量时,所以在 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());
}

此代码return

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

为什么最后一个值是 false,而之前是更改为 true?

感谢帮助

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);