javascript - 如何解释下面的例子?吊装?

标签 javascript hoisting

我试图解释 javascript 提升的问题,但我无法解释 b 的情况。

b = 50不是修改了全局变量b吗?

是 block 级作用域的原因吗?

环境

Chrome 77

{
  a = 50
  function a() {}
}
console.log(a) //  50
console.log(b) // undefined
{
  console.log(b) // f b () {}
  function b() {}
  b = 50
  console.log(b) // 50
}
console.log(b) // ƒ b () {}

我以为 ba 一样是 50。但它是一个函数。

最佳答案

这里发生了两件重要的事情

  1. 托管发生在一个函数中 - 将任何东西放在 {} 中被视为一个 block ,而不是一个函数。
  2. 函数声明被提升到变量之上 - 因此如果 var 和函数具有相同的名称,函数将获得优先权

console.log(x); // f() {} //hoisted with assignment since "x" is function
var x = 90;
function x() {}

console.log(a); // undefined // hoisting of child block-scope variable is never assigned not even if "a" is function
{
    console.log(a); // f(){}
    a = 50; //**while execution //since global scope "a" not assigned yet it takes the first assignment in this child-block
    console.log(a); // 50 // because value has been assigned to "a" already
    function a(){} // Ignored //function "a" was never hoisted over variable assignment
    console.log(a); // 50 // block scope has "a=50" attached to it
}
console.log(a); // 50 // global scope also has "a=50" attached to it


console.log(b) // undefined // hoisting of child block-scope variable is never assigned not even if "a" is function
{
  console.log(b) // f () {}
  function b() {} // While hoisting global scope and this block scope get "b" attached to their scope as a function
  b = 50 // var b is reassigned, but "b" attached to this block is only reassigned, since type is changed globally attached "b" is not reached
  console.log(b) // 50
}
console.log(b) // ƒ () {} // globally attached "b" is a function

关于javascript - 如何解释下面的例子?吊装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160871/

相关文章:

javascript - 如何在 Vue/Nuxt 中使用链接下载 PDF 文件

javascript - `${variableName}` 和 {variableName} 有什么区别?

javascript - 函数定义未提升

javascript - 为什么命名函数表达式的 "typeof"返回未定义?

当函数作为参数传递时,Javascript 函数提升不适用?

javascript - Watchify 没有正确处理源 map

javascript - 如何在 `bower install` 时将依赖项的版本附加到文件名

javascript - 在全局范围内声明两个同名函数时,第二个函数将被执行

javascript - 将 localStorage 值打印到 HTML 页面

javascript - 如果函数是在 if 条件下定义的,它会被提升吗?