[英]javascript: save a variable's value between calls?
我有一些看起来像这样的代码:
createEntity = function (imageSource, baseX, baseY) {
tmpIndex = images.length;
images[tmpIndex] = new Image();
entities[tmpIndex] = new Entity;
images[tmpIndex].onload = function () {
entities[tmpIndex].ready = true;
// How do I get the line above to use the value of tmpIndex
// that existed when it was created?
// That is to say, I want the images[1].onload function to
// change entities[1].ready, not entities[4].ready
// (assuming I created 5 objects sequentially
// before any images finished loading)
}
images[tmpIndex].src = imageSource;
entities[tmpIndex].x = baseX;
entities[tmpIndex].y = baseY;
}
createEntity("images/background.png", 0, 0);
createEntity("images/pawn1.png",0,0);
createEntity("images/pawn2.png",30,30);
createEntity("images/pawn3.png",60,60);
createEntity("images/pawn4.png",90,90);
问题是,当我依次加载所有5张图像时,如上面的代码所示,我的onload函数使用当前值tmpIndex触发,而不是函数创建时存在的值。 有没有一种简单的方法可以使实体[somenumber] .ready正确切换?
您需要将tmpIndex
声明为局部变量。 要进行此更改
tmpIndex = images.length;
至
var tmpIndex = images.length;
为什么tmpIndex
必须在createEntity函数之外可见? 如果不是,则在函数内部声明它,如下所示: var tmpIndex = images.length;
即使在createEntity
函数执行完后,您的onload
回调也将能够读取其值,因为它将保留对创建它的作用域的引用。
每个执行范围都不相同,因此,每次调用createEntity
您都会创建不同的范围和一个不同的onload回调函数,该函数存储对该执行范围的引用,因此可以使用在那里定义的变量。
究竟。 这是一个工作的JSfiddle示例,它捕获onerror而不是onload: http : //jsfiddle.net/bdn2775k/1/
这是启示性的部分:
//Don't forget to declare a local variable !
var tmpIndex = images.length;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.