开发者

Is there any reason to purposely introduce closures to prevent variable hoisting?

Consider this code:

for 开发者_运维问答(var j = 0; j < 10; j++){
    // ...
}

Assume that a for loop appears right after this one, which uses the same j counter variable. Netbeans complains that the second j redefines the first one, because of variable hoisting.

Is there any reason why or why not I should surround my loop with a closure:

(function(){
    for (var j = 0; j < 10; j++){
        // ...
    }
})();

... to prevent the variable hoisting behavior, and stop Netbean's complaints?


Javascript variables have function scope - not the block scope you are probably used to. (This is a big Javascript wart that we must get used to)

The usual style rules suggest that it is better is to declare all variables, including loop variables just once in the beginning of the function. (Don't declare them inside the for statement - it makes sense in other languages but not in Javascript).

Hopefully this causes your compiler to calm down.

(You don't need to worry about both loops using the same variable that much - the variable is reinitialized anyway)


Is it complaining because you are redeclaring var? You can remove the second var since it would already be in scope.


The problem is that javascript variables are not block scoped but function scoped

Suppose you have a snippet like this

function MyDemo(){
    var i = 0;
    for( var j = 0; j < 10; j++ ){
        ++i;
    }
    alert( i );
    alert( j );
}

In javascript j will be alerted as 10, while as in a block scoped language like C# or Java, it would be something like j not defined in the context

That being the problem, the solution is not to wrap it in a closure.

Why don't you use another variable or re-initialise the same variable without declaring again?

Useful Link: Explaining JavaScript Scope And Closures


Wrapping the loop in a closure seems unnecessary to me and could potentially cause issues if you're defining variables inside the for loop that you would like you use outside of the loop. For example:

(function() {
  for (var j = 0; j < 10; j++) {
    var foo = "bar"
  }
});

// foo is undefined here

Whereas:

for (var j = 0; j < 10; j++) {
  var foo = "bar"
}

// foo is defined here

From a micro-performance standpoint, the closure also creates unnecessary overhead since, as other people have said, if you take the var off of the second for loop, it should stop complaining.


99% of the time, the runtime performance hit of the extra function call is going to be irrelevant. What's more important is the extra code cluttering up your codebase and making things harder to read. I'd say don't wrap that in a function call just for your IDE's sake.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜