【问题标题】:How to explain the following examples? Hoisting?如何解释下面的例子?吊装?
【发布时间】:2019-09-30 02:36:39
【问题描述】:

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

b = 50没有修改全局变量b

这是块级作用域的原因吗?

环境

铬 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。但它是一个函数。

【问题讨论】:

  • {} 的位置对于 ..{} 内部的 console.log(b) 与外部不同 - 并不是这些信息有帮助!
  • {} 内的 console.log(b) 是正常的。在function b () {}之前是f b() {} ,在b = 50之后是50
  • 行为不一致。如果你在 Safari 中运行它,你会得到不同的结果。不过,Chrome 和 Firefox 似乎产生了相同的结果。

标签: javascript hoisting


【解决方案1】:

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

  1. 托管发生在函数中 - 将 {} 中的任何内容视为块,而不是函数。
  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

【讨论】:

  • b = 50 b 是局部变量吗?为什么不是全局变量?
  • 首先不要只考虑局部和全局,考虑变量如何在代码块中访问,即该变量附加到该代码块的范围,例如闭包如何附加到函数上。类似地,全局块有一个附加的变量“b”,并且块 {} 也将有一个附加到其范围的“b”变量。所以这两个块没有必要在它们的范围内附加相同的变量值
猜你喜欢
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 2023-04-06
相关资源
最近更新 更多