为什么代码片段会这样输出?

时间:2019-09-16 10:10:52

标签: javascript function closures lexical-scope

const phrase = 'Hello';

if (true) {
  const user = 'John';

  var sayHi = () => {
    console.log(`${phrase}, ${user}`);
  };
}

sayHi(); // Hello, John
console.log(user); // ReferenceError: user is not defined

user和sayHi都在if块中定义,但是sayHi在该块外部可用,而user则不在。为什么?

4 个答案:

答案 0 :(得分:1)

每当您使用var定义变量时,该变量都会被提升-这意味着其声明将移动到当前作用域的顶部。 但是,对于使用let / const创建的作用域变量,情况并非如此,其中变量仅在它们创建的作用域中定义

答案 1 :(得分:0)

const phrase = 'Hello';
const user = 'John';

if (true) {
  var sayHi = () => {
    console.log(`${phrase}, ${user}`);
  };
}

sayHi(); // Hello, John
console.log(user); // This will work now, this answer is similar to @Saurabh Agrawal

答案 2 :(得分:0)

块作用域是if,switch条件或for和while循环内的区域。一般而言,每当您看到{弯括号}时,它都是一个障碍。在ES6中,constlet关键字允许开发人员在块范围内声明变量,这意味着这些变量仅存在于相应的块内。

在您编程时,user的作用域常量只能在if块内部访问。 这就是为什么在undefined块外使用时得到if的原因。

请参阅此reference

答案 3 :(得分:0)

该变量是在if语句范围内使用'const'关键字创建的,简单来说,该变量是在开头'{'和结尾'}'内创建的,因此只能在方括号内进行访问,因为'const '和'let'具有块范围。 Check out the full explanation here.