function hoisting shows different results with and without block scope [duplicate]

问题: This question already has an answer here: What are the precise semantics of block-level functions in ES6? 2 answers This is the example:...

问题:

This question already has an answer here:

This is the example:

function b() {
  console.log(f); 

  {
    function f() {}
  }
}

b()

I thought it would become:

function b() {
  // hoist to function scope
  function f() {}
  console.log(f); // should output function f
}

or

function b() {
  console.log(f); // should output reference error
  {
     // just hoist to block scope like this
     function f() {}
  }
}

but it outputs undefined, like var hoisting. why?


回答1:

{} creates block scope so

JS engine will interpret your code something like this

function b() {
  console.log(f);
  {
    var f = function f() {};
  }
}

b();

So because of block scoping value of f is not available out of block. and since it is defined as var it is hoisted to parent's scope ( function b's scope ) and turns out to be undefined

If you remove {} .

function b() {
  console.log(f); 
  function f() {}
}

b()


回答2:

It's due to Hoisting. The function f() {} is inside a block, therefore console.log(f) cannot access the function f() {}, that is out of the scope. However, if you keep the console.log(f) inside the block {}. Hoisting should work.

  • 发表于 2019-02-22 05:27
  • 阅读 ( 161 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除