JS语法作用域问题。

最近在看JAVASCRIPT语言精粹与编程实践这本书。
书中讲了语法作用域

clipboard.png
clipboard.png

自己做了一下测试,效果好像不对。

clipboard.png
程序直接报错,func1 is not a function。
函数func2可以执行,因为对函数做了提升。
那么问题到底出在了哪里?各位大佬。

阅读 2.1k
3 个回答

这只是和写书的人的时间有关系,有些书会告诉你这个规则正在(已经)改变。这里所隐藏的是函数声明提升方式。

以下为ECMAScript标准,仅为了解释上诉错误,在任何情况下都不建议使用此标准。

Function statements are NOT declared during variable instantiation. They are declared at run time, just like function expressions. However, once declared, function statement's identifier becomes available to the entire scope of the function. This identifier availability is what makes function statements different from function expressions (you will see exact behavior of named function expressions in next chapter).
console.log(typeof foo); // "undefined"
if (true) {
  // once block is entered, `foo` becomes declared and available to the entire scope
  function foo() { return 1; }
} else {
  // this block is never entered, and `foo` is never redeclared
  function foo() { return 2; }
}
console.log(typeof foo); //

http://kangax.github.io/nfe/#...

说简单简单,说复杂复杂的
你把func1的定义放在判断之后,示例中也是这样的,这里涉及到哪种类先执行的问题

if(true){
    function func1(){
        console.log(56)
    }
}
func1()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题