Closures in a for loop and lexical environment

后端 未结 4 1202
青春惊慌失措
青春惊慌失措 2020-12-01 23:33

Simple case: I want to load several images which have a common name and a suffix, e.g: image0.png, image1.png, image2.png ... imageN.png

I\'m using a simple for loop

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 23:56

    The i inside your function is evaluated when the function is executed, not when you assign it to onload. Your for loop has already completed by the time any of your onload functions fire, so all of them see the final value N.

    To capture the current value of i, you need to pass it as a parameter to another function where it can be captured as a local variable:

    function captureI(i) {
        return function () {
            console.log("Image " + i + " loaded");
        };
    }
    
    var images = [];
    for (var i=1; i

    This works because every time you call captureI, a new local variable is created for that instance of captureI. In essence, you are creating N different variables and each onload function captures a different instance of the variable.

提交回复
热议问题