首页 > 解决方案 > 为什么当我尝试使用 IFFE 时这段代码不起作用

问题描述

我试图运行这段代码。

var temp = (function () {
var a =10;
return {
    function (a) {
        console.log('Value of a is ' + a);
    }
 }
})();
temp();

我希望 IIFE 返回该函数并将其分配给 temp 变量,但相反,我收到以下错误。

Uncaught TypeError: temp is not a function

那有什么问题?

标签: javascriptfunctioniife

解决方案


您需要从返回中删除对象文字并返回一个命名函数

var temp = (function() {
  var a = 10;
  return function test(a) {
    console.log('Value of a is ' + a);
  }
})();
temp();


推荐阅读