您误解了代码。该函数add()不包含代码var counter = 0。这是完全相同的代码的重写,使其更加清晰:var add;// Note: THIS function is NOT add()(function () { var counter = 0; // THIS function is add() add = function () {counter += 1; return counter}})();add(); // 1add(); // 2除了如何分配之外,上面的代码与原始代码执行的操作完全相同add。在您的代码中,它是通过返回值分配的,但在上面我只是将它直接分配为全局变量,以便更清楚哪个函数是add()。另一种更像原始代码的方式是显式命名这两个函数:var function1 = function () { var counter = 0; // The returned function is what will be assigned to add() return function () {counter += 1; return counter}}; // Do not call it yet since calling it was what was confusing youvar add = function1();add(); // 1add(); // 2