我读了很多关于这个论点的页面,但仍然不明白为什么这个(声明)
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/