在块范围内声明的函数和变量

Function and varible declar inside a block scope

有人可以解释这段代码的输出吗?我今天看到一个代码测试,但不理解输出。我知道它测试 ES6 块作用域。我对第一个没意见,但对其他人不满意。

{
  function test() {}
  test = 123
}
console.log(test)
console.log(typeof test)

{
  function test1() {}
  test1 = 123

  function test1() {}
}
console.log(test1)
console.log(typeof test1)

{
  function test2() {}
  test2 = 123

  function test2() {}
  test2 = 345
}
console.log(test2)
console.log(typeof test2)

谁能解释一下为什么输出是:

ƒ test() {}
function
123
number
123
number

"use strict" 应该可以帮助您避免这种奇怪的行为。

我终于找到了答案,我知道没有人会写出与我发布的完全相同的代码,直接使用块,但是,如果你看到这个,,如果我们不这样做,我们可能会写错代码对 JS 中的作用域有很好的理解。我应该提到代码在 ES6 中应该 运行 而不是 ES5 严格模式 ,还要提到它在 Chrome 上 运行ning 浏览器支持 ES6,很抱歉让 vikarpov 感到困惑。

基于,http://www.ecma-international.org/ecma-262/6.0/#sec-additional-ecmascript-features-for-web-browsers,B.3.3,Block-Level Function Declarations Web Legacy Compatibility Semantics,在 ES6 中,块中的函数声明使用 ES6 声明语义(如 let 或 const),这确实不允许重新声明。

所以答案是

{
  function test() {}
  test = 123
}
console.log(test)
console.log(typeof test)

将是

var test
{
    let test = function test() {};
    window.test1 = test1
    test = 123;
}
console.log(test) //f test(){}
{
  function test1() {}
  test1 = 123

  function test1() {}
}
console.log(test1)
console.log(typeof test1)

将会

var test1
{
    let test1 = function test1() { }
    window.test1 = test1
    test1 = 123
    window.test1 = test1
}
console.log(test1) //123
{
  function test2() {}
  test2 = 123

  function test2() {}
  test2 = 345
}
console.log(test2)

将会

var test2
{
    let test2 = function test2() {}
    window.test2 = test2
    test2 = 123
    window.test2 = test2
    test2 = 345
}
console.log(test2)