为什么 iife 不能在一个简单的例子中工作?

Why iife not working in a simple example?

我不明白为什么函数表达式调用不起作用并抛出错误。

你能给我解释一下吗?

var a = function (x) {
  alert(x)
}

(function() {
   a(1);
}());

感谢大家

任务比我想象的要容易得多

在IIFE中定义函数a参考here

(function() {
  function a(x) {
    alert(x)
  }
  a('x')
}());

因为此刻,在你调用函数的地方,赋值还没有发生。

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);
}());

那是因为JS将IIFE解析为函数的参数调用,这样加分号就可以了

var a = function (x) {
  alert(x)
};    
(function() {
   a(1);
}());