让变量和块作用域 [英] Let variables and block scope

查看:94
本文介绍了让变量和块作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一个控制台日志应该打印出"Ken"时却打印出"James"? let'student'变量不应该作为'if-statement'的范围并保留其值为"Ken"的范围吗?另外,当我重新声明相同的变量名称"student"时,是否应该不会出现错误?

Why does the first console log print out "James" when it should print out "Ken"? Shouldn't the let 'student' variable be scope to the 'if-statement' and retain its value as "Ken"? Also, shouldn't there be an error as I'm redeclaring the same variable name 'student'?

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

推荐答案

let是块作用域的,因此以下代码行:

let is block scoped so this line of code:

let student = {name: name};

仅限于if语句内的括号.所以,以后再做

is scoped only to the brackets inside the if statement. So, when you later do

return student;

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

outside of the if block and outside of where the other student variable was defined, that variable is no longer in scope so the only student variable that is in scope is the James one.

这是带注释的版本:

(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);
})();

让'student'变量不属于'if-statement'并保留其值为"Ken"吗?

Shouldn't the let 'student' variable be scope to the 'if-statement' and retain its value as "Ken"?

它的作用域仅限于if语句.但是,当您执行return时,它位于该块之外,因此不再可以访问Ken学生变量,因此,范围内的唯一变量是James.

It is block scoped to the if statement. But, when you do the return, it's outside that block so there is no access to the Ken student variable any more so the only one that is in scope is the James one.

而且,当我重新声明相同的变量名'student'时,应该不会出现错误吗?

Also, shouldn't there be an error as I'm redeclaring the same variable name 'student'?

定义已经在更高范围内定义的变量不是错误.相反,新声明会在该范围内遮盖或隐藏另一个声明,从而在该范围内暂时将其覆盖.

It is not an error to define a variable that was already defined in a higher scope. Instead, the new declaration shadows or hides the other declaration within that scope, temporarily overriding it within that scope.

这篇关于让变量和块作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆