关于JavaScript自执行函数外层额外()作用的技术咨询
Hey there! Let's break down those confusing extra parentheses in your code—they're part of an Immediately Invoked Function Expression (IIFE) (aka an "immediately executed function"), and they serve two key purposes.
First, let's look at your code again for context:
const sum = (function() { return function sum(...args) { return args.reduce((a, b) => a + b, 0); }; })(); console.log(sum(1, 2, 3, 4)); // Output: 10
What do the two sets of parentheses do?
The outer wrapping parentheses
(function() { ... })
Normally, if you writefunction() { ... }on its own, JavaScript treats it as a function declaration—which can't be immediately called. By wrapping the function in parentheses, we turn it into a function expression. This tells JavaScript: "Hey, this is a value (a function) that I can use right away, not just a named declaration to define later."The trailing parentheses
()
This is the actual function call! Once we've turned the function into an expression with the first set of parentheses, adding()right after it tells JavaScript to execute that function immediately.
In your code, here's what happens step-by-step:
- The wrapped function runs instantly.
- It returns the inner
sum(...args)function (the one that does the actual addition). - That returned function gets assigned to the global
sumvariable. - When you call
sum(1,2,3,4)later, you're calling that inner function.
Why use this pattern?
In your specific example, you could simplify the code to this and get the same result:
const sum = function sum(...args) { return args.reduce((a, b) => a + b, 0); };
The IIFE pattern shines when you want to create a private scope for variables. Any variables declared inside the outer function won't be accessible from the global scope, which helps avoid naming collisions. For example:
const sum = (function() { // This variable is private to the IIFE—global code can't access it const calculationLog = []; return function sum(...args) { const total = args.reduce((a, b) => a + b, 0); calculationLog.push(total); // Inner function can access the private variable return total; }; })();
Here, calculationLog is hidden from the rest of your code, but the inner sum function can still use it—this is a basic form of encapsulation in JavaScript.
内容的提问来源于stack exchange,提问作者victor senior

