当我在加载图像后更改变量时,所以在游戏循环中我有旧的价值..
我做错了什么?
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
为什么最后一个值为false,前一个值变为true?
感谢您的帮助
答案 0 :(得分: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);