boxSize 泄漏到全局范围

boxSize leaking to globalscope

控制台日志两次,但只需要显示第一个 console.log(boxSize)

var size = 100;
if (size > 50) {
    var boxSize = size * 5;
    console.log(boxSize);
}
console.log(boxSize);

我建议为此使用 let over var

The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.

来源:

示例:

var size = 100;

/* Using Var */
if (size > 50) {
  var varExample = size * 5;
  console.log("With var inner: " + varExample);
}
console.log("With var outer: " + varExample);

/* Using Let */
if (size > 50) {
  let letExample = size * 5;
  console.log("With let inner: " + letExample);
}
console.log("With let outer: " + letExample);

这是在 Javascript 中称为 提升 的行为。

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

var in javascript 不是块范围的。 您可以在 ES6 中使用关键字 letconst 来声明仅可用于声明它的块的变量。

var size = 100;
if (size > 50) {
    let boxSize = size * 5;
    console.log(boxSize);
}
console.log(boxSize);// Uncaught ReferenceError: boxSize is not defined

let size = 100;
if (size > 50) {
  let boxSize = size * 5;
    console.log(boxSize);
}
console.log(boxSize);
/* Es6 let declers a block scope
  local variable(not function level scope like var)
  */
  //trying to access the variable in the block before the variable declaration resulsts in a ReferenceError