简体   繁体   English

javascript:在调用之间保存变量的值?

[英]javascript: save a variable's value between calls?

I have some code that looks like this: 我有一些看起来像这样的代码:

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

The problem is that when I load all 5 images sequentially, as the above code shows, my onload function triggers with the current value of tmpIndex, not the one that existed when the function was created. 问题是,当我依次加载所有5张图像时,如上面的代码所示,我的onload函数使用当前值tmpIndex触发,而不是函数创建时存在的值。 Is there a simple way to make it so that the entities[somenumber].ready is toggled appropriately? 有没有一种简单的方法可以使实体[somenumber] .ready正确切换?

You need to declare tmpIndex as a local variable. 您需要将tmpIndex声明为局部变量。 To do this change 要进行此更改

tmpIndex = images.length;

to

var tmpIndex = images.length;

Why does tmpIndex have to be visible outside of createEntity function? 为什么tmpIndex必须在createEntity函数之外可见? If it doesn't, just declare it inside your function, like this: var tmpIndex = images.length; 如果不是,则在函数内部声明它,如下所示: var tmpIndex = images.length;

Your onload callback will be able to read its value even after the createEntity function has finished executing because will keep a reference to the scope where it was created. 即使在createEntity函数执行完后,您的onload回调也将能够读取其值,因为它将保留对创建它的作用域的引用。

Every execution scope is different, so every time you call createEntity you create different scope and a different onload callback function which stores a reference to that execution scope, and therefore is able to consume variables defined there. 每个执行范围都不相同,因此,每次调用createEntity您都会创建不同的范围和一个不同的onload回调函数,该函数存储对该执行范围的引用,因此可以使用在那里定义的变量。

Exactly. 究竟。 Here's a working JSfiddle example catching onerror instead on onload : http://jsfiddle.net/bdn2775k/1/ 这是一个工作的JSfiddle示例,它捕获onerror而不是onload: http : //jsfiddle.net/bdn2775k/1/

Here's the revelant part : 这是启示性的部分:

//Don't forget to declare a local variable !
var tmpIndex = images.length;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM