开发者

Can JavaScript get confused between local variables?

If I have a pair of functions开发者_如何转开发 that both set local variables, for example, the variable i in common for loops, and one happens to be called while the other is running, is there any danger of namespace confusion?


Keep in mind that JavaScript does not have block scope, but only function scope.

In addition, if you have nested loops, there will only be one i variable in the following example:

function myFunction() {
  for (var i = 0; i < 10; i++) {
    for (var i = 0; i < 10; i++) {
      // code here will run 10 times instead of 100 times
    }
  }
  // variable i is still accessible from here
}

Douglas Crockford recommends that the var statements should be the first statements in the function body in Code Conventions for the JavaScript Programming Language:

JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.

I think he has a point, as you can see in the following example, which will not confuse readers into thinking that the variables i and j are held in the scope of the for loop blocks:

function myFunction() {
  var i, j;    // the scope of the variables is now very clear
  for (i = 0; i < 10; i++) {
    for (j = 0; j < 10; j++) {
      // code here will run 100 times
    }
  }
}


As long as you're using var, like this:

for(var i = 0; i < something; i++)

Then it's local and you're fine, if you don't use var, you have a global variable on your hands, and potential issues. Also if a for loop is nested in another, you should use a different variable name for each loop.


It will be a problem if are you referring to nested loops. Every time you enter the second for loop, the value of i (previously set in the outer for loop) will be reset.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜