This question already has answers here:
Javascript function scoping and hoisting
                                
                                    (16个答案)
                                
                        
                        
                            Are variables declared with let or const not hoisted in ES6?
                                
                                    (4个答案)
                                
                        
                3个月前关闭。
            
        

使用较旧的语法

打印“这是myfunc1”

myfunc1();

function myfunc1() {
console.log("this is myfunc1");
}


使用es6语法
这给出了错误“ myfunc2不是函数”

myfunc2();

var myfunc2 = () => {
  console.log("this is myfunc2");
}

最佳答案

函数声明被提升。

使用var关键字的变量声明也会被挂起(这意味着Javascript引擎“知道”已声明该变量),但是由于未挂起赋值,因此该变量将包含undefined直到执行执行该赋值的代码行。



不要考虑这种“旧”和“新”语法。

函数声明,函数表达式和箭头函数均具有different behaviour。尽管箭头函数是最近才引入该语言的,但它们不能替代函数声明或函数表达式。

10-04 22:38
查看更多