Javascript 块范围内的函数和变量declar

Javascript 块范围内的函数和变量declar,javascript,ecmascript-6,variable-declaration,Javascript,Ecmascript 6,Variable Declaration,有人能解释一下这段代码的输出吗?我今天看到一个代码测试,不理解输出。我知道它测试ES6块范围。我对第一个没意见,但对其他的没意见 { 函数测试(){} 测试=123 } console.log(测试) 控制台日志(测试类型) { 函数test1(){} test1=123 函数test1(){} } console.log(test1) console.log(test1的类型) { 函数test2(){} test2=123 函数test2(){} test2=345 } console.l

有人能解释一下这段代码的输出吗?我今天看到一个代码测试,不理解输出。我知道它测试ES6块范围。我对第一个没意见,但对其他的没意见

{
函数测试(){}
测试=123
}
console.log(测试)
控制台日志(测试类型)
{
函数test1(){}
test1=123
函数test1(){}
}
console.log(test1)
console.log(test1的类型)
{
函数test2(){}
test2=123
函数test2(){}
test2=345
}
console.log(test2)

console.log(typeof test2)
“使用严格”应该可以帮助您避免这种奇怪的行为。

我终于找到了答案,我知道没有人会编写与我发布的完全相同的代码,直接使用block,但是,如果您看到这一点,如果我们对JS中的范围没有很好的理解,我们可能会编写错误的代码。我应该提到代码应该在ES6而不是ES5严格模式下运行,还应该提到它在Chrome上运行,浏览器支持ES6,很抱歉混淆了vikarpov

基于B.3.3块级函数声明Web遗留兼容性语义,在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(){}
将是

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

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

块语句和隐式全局函数中的函数声明。。。这真的不是一个实用的编程问题,两者都是一个大问题。是的,我绝对同意这不是一个好的行为。我相信没有人会这么做。我在一个采访问题列表中看到了这一点……实际上,根据有条件创建的函数,并不是所有浏览器都将函数提升。在对非严格代码中的块级函数进行了多次研究之后,我应该说输出是不正确的。我只在Chrome上测试过,但是,在我检查了MDN,on,有条件创建的函数之后,结果不一样。为了避免这种有线输出,我们可以使用严格模式,一种安全的方法是使用函数表达式,就像这里说的,在块级函数中使用非严格代码。