无需定义变量两次

Car*_*Gil 5 javascript variables

如果可以在函数中定义变量,即使没有赋值,它也会变为局部变量

那么,testB()更好的编程吗?

var test = 'SNAP!'
function testA(boolean) {
    if (boolean) var test = 'OK';
    else var test = null;
    alert(test);
}
function testB(boolean) {
    if (boolean) var test = 'OK';
    alert(test);
}
testA(true); // 'OK'
testB(true); // 'OK'
testA(false); // null
testB(false); // undefined, no error
Run Code Online (Sandbox Code Playgroud)

在我的具体案例中,测试的全局值('SNAP!')既不是预期也不是必需的.

CMS*_*CMS 6

您无法有条件地声明变量.

为什么?

变量实例化过程发生实际代码执行之前,在执行函数时,这些变量已经绑定到本地范围,例如:

function foo () {
  if (false) {
    var test = 'foo'; // never executed
  }
  return test;
}
foo(); // undefined
Run Code Online (Sandbox Code Playgroud)

当函数即将被执行时,形式参数的标识符,来自变量声明的标识符和函数体内函数声明的标识符被绑定到局部变量环境.

变量初始化为undefined.

此外,在局部范围内标识阴影别人使用相同的名称,在较高的范围链,例如:

var test = 'global';
function bar () {
  alert(test); // undefined, not "global", the local variable already declared
  var test = 'xxx';
}
bar();
Run Code Online (Sandbox Code Playgroud)

如果test变量未在任何地方声明,ReferenceError则抛出a:

function foo () {
  return test;
}

try {
  foo(); // ReferenceError!!
} catch (e) {
  alert(e);
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么例如JSLint建议在函数顶部只有一个var语句的原因之一,因为例如,第一个片段在执行时实际上类似于:

function foo () {
  var test; // var statement was "hoisted"
  if (false) {
    test = 'foo'; // never executed
  }
  return test;
}
foo(); // undefined
Run Code Online (Sandbox Code Playgroud)

另一个原因是因为块不引入新的词法范围,只有函数执行它,因此var在外观中使用语句可能会让您认为变量的生命仅限于该块,但事实并非如此.

嵌套函数声明将具有类似的提升行为,它们将在代码执行之前声明,但它们也在那一刻初始化:

function foo () {
  return typeof bar;
  // unreachable code:
  function bar() {
    //..
  }
}
foo(); // "function"
Run Code Online (Sandbox Code Playgroud)