【问题标题】:Let variables and block scope让变量和块范围
【发布时间】:2017-06-19 03:29:33
【问题描述】:

为什么第一个控制台日志应该打印出“Ken”时却打印出“James”?不应该让“学生”变量成为“if语句”的范围并将其值保留为“Ken”吗?另外,当我重新声明相同的变量名“学生”时,不应该出现错误吗?

(function (){
    let student = {name: 'James'};
    function createStudent(name){
        if(true){
         let student = {name: name};
        }
        return student;
    }
    console.log(createStudent('Ken'));
    console.log(student);
})();

【问题讨论】:

  • 要记录 'Ken',在 if {} 条件中使用 return 语句。

标签: ecmascript-6 let


【解决方案1】:

let 是块作用域,所以这行代码:

let student = {name: name};

仅适用于 if 语句中的括号。所以,当你以后这样做时

return student;

if 块之外和另一个student 变量的定义位置之外,该变量不再在范围内,因此唯一在范围内的student 变量是James 变量。

这是一个带注释的版本:

(function (){
    let student = {name: 'James'};
    function createStudent(name){
        if(true){
         // define new student variable that is only in scope
         // within this block
         let student = {name: name};
        }
        // here, the student variable on the previous line is no longer
        // in scope so referencing it here sees the first declaration
        return student;
    }
    console.log(createStudent('Ken'));
    console.log(student);
})();

不应该让“学生”变量成为“if语句”的范围并将其值保留为“Ken”吗?

它的块范围为if 语句。但是,当您执行return 时,它位于该块之外,因此无法再访问Ken 学生变量,因此范围内的唯一变量是James

另外,当我重新声明同一个变量名“学生”时,不应该有错误吗?

定义已经在更高范围内定义的变量不是错误。相反,新声明会隐藏或隐藏该范围内的其他声明,暂时覆盖该范围内的其他声明。

【讨论】:

  • 感谢您解释如何在 if 块之外返回变量,将引用外部作用域的变量分配。至于你为什么在重新声明名为'student'的同一个变量时没有错误的答案:“定义已经在更高范围内定义的变量不是错误。”我在这里看到一个错误:let a = 'bar'; function foo(){ let a = 'baz'; console.log(a); } console.log(a);
  • 没关系 - 出于某种原因,我在 chrome 控制台中输入此内容时看到了一个错误。但我继续使用 repl.it,它运行良好。是因为 let 变量的作用域不同吗?再次感谢您的帮助!
【解决方案2】:

letconst 不像 var 在块语句中创建本地范围。您没有收到错误,因为新变量 阴影 范围之外的那个。

【讨论】:

    猜你喜欢
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    相关资源
    最近更新 更多