我无法理解为什么函数表达式调用不起作用并抛出错误。
你能解释一下吗?
var a = function (x) {
alert(x)
}
(function() {
a(1);
}());
谢谢大家
这项任务比我想象的容易得多
这是因为JS正在解析IIFE作为函数的参数调用,使用添加的分号这样做
var a = function (x) {
alert(x)
};
(function() {
a(1);
}());
因为此时,您调用该函数的位置尚未发生任务。
var a; // hoisted, value undefined, no function
// later
a = function (x) {
alert(x);
}(function() {
a(1); // a is still no function
}());
或者您需要插入分号以将分配与呼叫分开,
var a = function(x) {
console.log(x);
};
(function() {
a(1);
}());
或采取void
分离
var a = function(x) {
console.log(x);
}
void (function() {
a(1);
}());
定义IIFE内部的功能参考here
(function() {
function a(x) {
alert(x)
}
a('x')
}());