Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

javascript - Closures in a for loop and lexical environment

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:

var images = [];
for (var i=1; i<N; i++) {
    images[i] = new Image();
    images[i].onload = function () {
        console.log("Image " + i + " loaded");
    };
    images[i].src = "image" + i + ".png";
}

What I'm getting in the Console is:

Image N loaded
Image N loaded
Image N loaded
...
Image N loaded

But what I want should be like this:

Image 0 loaded
Image 1 loaded
Image 2 loaded
...
Image N loaded

Why is this happening? How can I get my desired behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<N; i++) {
    images[i] = new Image();
    images[i].onload = captureI(i);
    images[i].src = "image" + i + ".png";
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...