【问题标题】:Advantages of using let over var within a function [duplicate]在函数中使用 let over var 的优点 [重复]
【发布时间】:2016-09-18 01:53:26
【问题描述】:

假设我有一段这样的代码:

const number = 3;

function fooFunction() {
  let numberTwo = 5;
  var answer = number + numberTwo;
  return answer;
}

finalAnswer = fooFunction();

console.log(finalAnswer);

假设一个 ES2015 兼容的浏览器,使用上述代码的优点/缺点是什么,超过:

const number = 3;

function fooFunction() {
  var numberTwo = 5;
  var answer = number + numberTwo;
  return answer;
}

finalAnswer = fooFunction();

console.log(finalAnswer);

鉴于它们都返回相同的数字,有什么优点或缺点吗?

【问题讨论】:

  • 根据this answer,它们在像你这样的函数中是相同的
  • 从安全和性能的角度来看呢?
  • 按照你上面的用法,没有区别。
  • 如果在安全性或性能方面存在差异,它们就不会完全相同
  • 不,var 被提升到函数的顶部,而不是函数之外:)

标签: javascript function ecmascript-6 encapsulation var


【解决方案1】:

正如其他人所提到的,在您的示例中,您可以交替使用 let 和 var。区别在于let 是块作用域,而var 不是。

例如使用var,您可以这样做(打印“foo”):

function printFoo(param) {
  if (param) {
    var x = "foo";
  }

  console.log(x);
}

printFoo("hello");

您不能对 let 执行此操作,因为 let x 的范围仅限于 if 块,因此未定义。

【讨论】:

    【解决方案2】:

    在您提供的代码示例中,两者可以互换。 let 派上用场的地方是将范围限制在块级而不是函数级。例如,在 for 循环内使用 let。

    值得注意的是,使用var 关键字创建的变量会被提升,而使用let 关键字创建的变量不会。

    Kyle Simpson 在 David Walsh 的博客上对此主题进行了出色的细分:https://davidwalsh.name/for-and-against-let#implicit-hazards

    【讨论】:

    • 从技术上讲,let 变量被提升,但不可引用。见时间死区。 In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
    猜你喜欢
    • 2014-11-16
    • 2018-06-08
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2016-05-18
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多