函数声明的问题

变量声明中

    var fn = function fn2() {}
    
    console.log(fn) // function
    console.log(fn2) // Uncaught ReferenceError: fn2 is not defined

这里的fn2为什么是not defined? 是因为在fn2自己的作用域中么?

阅读 1.7k
3 个回答

javascript the definitive guide 8.1

An identifier that names the function. The name is a required part of function declaration statements: it is used as the name of a variable, and the newly defined function object is assigned to the variable. For function definition expressions, the name is optional: if present, the name refers to the function object only within the body of the function itself.

就是说,「赋值函数定义式」中的 identifier(函数名)是可选的,即使提供,也只能在函数体内引用;

fn2只能在fn2中才能引用的到

新手上路,请多包涵

function fun2(){}
var fn = fn2
console.log(fn)
console.log(fn2)

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