【问题标题】:Why does the "typeof" of a named function expression return undefined? [duplicate]为什么命名函数表达式的“typeof”返回未定义? [复制]
【发布时间】:2019-10-09 01:44:41
【问题描述】:

我是 JS 新手,如果这听起来很愚蠢,请原谅我。我在玩函数声明函数表达式的概念。

我有以下代码:

var printSomething = function printSomeString(string) {
  console.log(string);
}

console.log(typeof printSomething); // function
console.log(typeof printSomeString); // undefined

如果我按照 JavaScript 中 hoisting 的定义,当我使用 printSomethingprintSomeString 时,它们应该可用,因为它们的声明已被提升。

typeof printSomething 返回函数,但 typeof printSomeString 返回未定义。为什么这样?

这个命名函数表达式在使用之前不是已经声明和提升了吗?

命名函数表达式本身不是函数吗?

另外,当我调用printSomeString('Some STRING') 时,它会返回以下内容

Uncaught ReferenceError: printSomeString is not defined

这是怎么回事?

【问题讨论】:

标签: javascript hoisting function-declaration function-expression


【解决方案1】:

printSomeString 不是一个全局变量,它是另一个函数printSomething 的局部变量。尝试在其中使用console.log()

var printSomething = function printSomeString(string) {
  console.log(typeof printSomeString)
}

console.log(typeof printSomething); // function
printSomething()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2019-12-20
    • 2017-07-16
    相关资源
    最近更新 更多