这个while循环有什么区别?

Mir*_*rod 2 javascript

有什么区别

while(condition){
    var variable;   
    ...
}
Run Code Online (Sandbox Code Playgroud)

while(condition){(function(){
    var variable;   
    ...
})();}
Run Code Online (Sandbox Code Playgroud)

有人可以解释我的干涉吗?

Dar*_*rov 7

在第一种情况下,变量可以在while(甚至在它之后)的任何地方访问.在第二种情况下,它是私有的,只能在自动调用匿名函数中访问.所以差异基本上在变量的范围内.第二个例子看起来很复杂而没有提供更多的上下文.

第一个例子:

while(condition) {
    var variable;   
    ... // the variable is accessible here
}

// the variable is accessible here
Run Code Online (Sandbox Code Playgroud)

第二个例子:

while(condition) {
    (function() {
        var variable;   
        ... // the variable is accessible here
    })();

    // the variable is NOT accessible here
}

// the variable is NOT accessible here
Run Code Online (Sandbox Code Playgroud)

  • 在第一种情况下,变量可以在包含while()语句的函数内的任何位置访问; 它不会在结束时超出范围. (2认同)
  • 令我害怕的是,在任何人抱怨之前,这个得到了+5. (2认同)