gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:15:34 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com