JavaScript中调用返回函数的函数方法及代码相关疑问解析
Let's walk through your question piece by piece—this is a perfect example of closures, a key concept in JS that trips up a lot of folks at first!
First, let's recap your code for reference:
function getFunc() { var a = 7; return function(b) { alert(a+b); } } var f = getFunc(); f(5);
Why can't you just call getFunc(5) directly?
The getFunc function itself doesn't accept any parameters—look at its definition: function getFunc() has an empty parameter list. If you run getFunc(5), here's what happens:
getFuncexecutes, creates the variablea = 7, and returns the inner anonymous function.- That returned function gets immediately discarded (since you don't store it or call it), so nothing pops up. The
5you passed is ignored becausegetFuncdoesn't have a parameter to catch it.
What's the point of assigning the function to var f?
Let's break down those two lines:
var f = getFunc();: When you callgetFunc(), it runs its code, createsa = 7, and hands back the inner function. This inner function "remembers" the environment it was created in—meaning it still has access to thata = 7variable, even aftergetFunchas finished running. We store this inner function infso we can use it later.f(5);: Now we're calling the inner function we stored inf. This is where we pass the5as the parameterbthat the inner function expects.
What happens when you run f(5)?
- You invoke the inner function (stored in
f) and pass5to itsbparameter. - The function tries to compute
a + b. It doesn't have its ownavariable, so it looks up to the outer scope where it was created—the scope from whengetFunc()ran, wherea = 7still exists (thanks to closures!). - It calculates
7 + 5 = 12and triggers the alert with that value.
How does JS know to pass 5 to the inner function instead of the outer one?
It's all about which function you're calling:
- When you call
getFunc(), you're invoking the outer function, which has no parameters. Any arguments you pass here (like5) are ignored because there's no parameter to receive them. - When you call
f(5), you're invoking the inner function, which is defined withfunction(b). JS knows to assign5tobbecause that's the parameter list of the function you're actually calling.
This ability of an inner function to retain access to variables from its outer scope even after the outer function has completed is called a closure—it's one of JS's most powerful (and often misunderstood) features!
内容的提问来源于stack exchange,提问作者user3808307

