javascript - 函数声明与函数表达式 : what will be printed in this case?

标签 javascript function

我读了很多关于这个论点的页面,但仍然不明白为什么这个(声明)

function foo() {console.log("foo");}

(function(){
  // Really there is nothing here
})();

什么都不做,而这个(表达式)

var foo = function() {console.log("foo");}

(function(){
  // Really there is nothing here
})();

输出

foo

Uncaught TypeError: undefined is not a function

这里发生了什么?

最佳答案

正如 Felix Kling 指出的那样,您在分配后缺少分号。

第二个匿名函数周围的括号将被解释为函数调用参数周围的括号:

var foo = function() {console.log("foo");}(function(){ })();

表达式 function() {console.log("foo");}(function(){ }) 将返回 undefined 因为没有 return 语句第一个功能。最后一对括号将使其成为另一个函数调用,但由于 undefined 不是函数,您会收到特定的错误消息。

关于javascript - 函数声明与函数表达式 : what will be printed in this case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12143688/

相关文章:

javascript - Facebook 错误 : (#100) The specified scheduled publish time is invalid

javascript - 避免局部最优训练 XOR

c - 带有 C 语言函数的简单无限循环

python - 递归整合

javascript - 在自定义事件中访问 javascript 本地变量

javascript - 比较 if 语句的快捷方式

javascript - HttpClientXsrfModule 是否仍然需要在服务器上设置 XSRF-TOKEN?

c++ - 将函数用作非类型模板参数时出错

javascript - 将函数插入另一个函数中?

javascript - Chrome 扩展 - 使用现有功能