You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中调用返回函数的函数方法及代码相关疑问解析

Understanding Closures in Your JavaScript Example

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:

  1. getFunc executes, creates the variable a = 7, and returns the inner anonymous function.
  2. That returned function gets immediately discarded (since you don't store it or call it), so nothing pops up. The 5 you passed is ignored because getFunc doesn'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 call getFunc(), it runs its code, creates a = 7, and hands back the inner function. This inner function "remembers" the environment it was created in—meaning it still has access to that a = 7 variable, even after getFunc has finished running. We store this inner function in f so we can use it later.
  • f(5);: Now we're calling the inner function we stored in f. This is where we pass the 5 as the parameter b that the inner function expects.

What happens when you run f(5)?

  1. You invoke the inner function (stored in f) and pass 5 to its b parameter.
  2. The function tries to compute a + b. It doesn't have its own a variable, so it looks up to the outer scope where it was created—the scope from when getFunc() ran, where a = 7 still exists (thanks to closures!).
  3. It calculates 7 + 5 = 12 and 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 (like 5) are ignored because there's no parameter to receive them.
  • When you call f(5), you're invoking the inner function, which is defined with function(b). JS knows to assign 5 to b because 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:27:35