Tiny question about closure of javascript
I want to change the element's width in order to do a simple animation here's the code:
function mysildeDown(elem) {
var fullw = parseInt(getStyle(elem, 'width'));
elem.style['width'] = 0;
for (var j=0; j < 100; j++) {
(function () {
**var i=j;**
setTimeout(function () {
elem.style['width'] = (i / 100) * fullw + 'px';
开发者_高级运维 }, (i + 1) * 10 );
})();
}
}
//the GetStyle function is no problem
I wonder why should I use var i=j ,Thanks a lotGenerally when doing something like this inside of a loop, and using the value of j in another function, the function always ends up with the last value of j. So, you need to find a way to use the value of j as it was when you created that function inside the loop.
The way I normally see is to pass it in as a parameter in the immediately invoked function as below.
function mysildeDown(elem){
var fullw=parseInt(getStyle(elem,'width'));
elem.style['width']=0;
for(var j=0;j<100;j++){
(function(i){
setTimeout(function(){
elem.style['width']= (i/100)*fullw+'px';
},(i+1)*10)
})(j);
}
}
using the var
keyword when defining a variable in javascript declares it within the scope of the current line of code. In your specific case, if you didn't use the var
keyword when declaring variable i
then i
would be global, potentially causing problems as it's so commonly used in for
loops.
By using the var
keyword, inside a function, your variable i
is local to the function and is not accessible outside the scope of that function.
There is some good info here.
So that i will have the value of j within the timer function at the time setTimeout was called. Essentially, you are storing the value of j to be used when the timer fires.
精彩评论