简体   繁体   中英

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. Is there a simple way to make it so that the entities[somenumber].ready is toggled appropriately?

You need to declare tmpIndex as a local variable. To do this change

tmpIndex = images.length;

to

var tmpIndex = images.length;

Why does tmpIndex have to be visible outside of createEntity function? If it doesn't, just declare it inside your function, like this: 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.

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.

Exactly. Here's a working JSfiddle example catching onerror instead on onload : http://jsfiddle.net/bdn2775k/1/

Here's the revelant part :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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