立即调用的函数表达式运行最后定义的函数。为什么?
Immediately invoked function expressions runs the last defined function. Why?
我遇到了一些奇怪的行为,我没想到在使用立即调用的函数表达式时会发生这些行为。当末尾有 IIFE 时,下面的代码运行函数 hello
。为什么会这样?
var hello = function () {
console.log("hello");
}
(function () {
})();
运行这个,不会
var hello = function () {
console.log("hello");
};
(function () {
})();
这是因为 JavaScript 解释器将其理解为连续代码,除非您使用 ;
将其标记为语句的结尾。
您的代码
var hello = function () {
console.log("hello");
}
(function () {
})();
居然变成这样
var hello = function () {
console.log("hello");
}(function(){})();
并且解释器通过将 function () {}
作为参数立即运行 hello
函数,并为下一个 ()
.
抛出错误
我遇到了一些奇怪的行为,我没想到在使用立即调用的函数表达式时会发生这些行为。当末尾有 IIFE 时,下面的代码运行函数 hello
。为什么会这样?
var hello = function () {
console.log("hello");
}
(function () {
})();
运行这个,不会
var hello = function () {
console.log("hello");
};
(function () {
})();
这是因为 JavaScript 解释器将其理解为连续代码,除非您使用 ;
将其标记为语句的结尾。
您的代码
var hello = function () {
console.log("hello");
}
(function () {
})();
居然变成这样
var hello = function () {
console.log("hello");
}(function(){})();
并且解释器通过将 function () {}
作为参数立即运行 hello
函数,并为下一个 ()
.