似乎 3 有点存储在函数“内部”中,在第二次调用期间将其与 5 相加并返回 8。
没错。对outside 的每次调用都会创建一个新 inside 函数,并且该函数将调用outside 的数据绑定到它。它“关闭”了这些数据。这些被称为“闭包”。不要让这个名字打扰你,closures are not complicated。
与第一次调用不同,第二次调用外部(outside(3)(5))返回值(8)而不是内部函数(inside)如何?
对outside 的第二次调用确实返回一个函数(该调用生成的inside 函数);但随后您会立即使用第二对 () 调用该函数。
线
outside(3)(5);
...分解如下:
var f = outside(3); // Create and get the `inside` function bound to 3
f(5); // Call it, passing in `5`
来自您的评论:
所以你的意思是,在outside(3) 的第一次调用中,“返回”的inside 方法定义变为(更改为?)返回3 + y;。是这样吗?
关闭,但不完全。 x 的值不会被烧入inside; inside 具有对创建它的上下文的引用,并且该上下文使其可以访问 x 参数。这些并不完全相同,我们可以看到如果我们稍微更新一下示例(并放弃数学,这只会使事情变得模糊):
function outside(name) {
// 'inside' uses the 'name' argument from the call to 'outside' that created it
function inside() {
return name;
}
// 'changer' *changes* the 'name' argument's value
function makeCaps() {
name = name.toUpperCase();
}
// Return both of them
return {
inside: inside,
makeCaps: makeCaps
};
}
var funcs = outside("foo");
funcs.inside(); // "foo", because 'inside' uses the 'name' created
// by the call to 'outside', and that 'name' is
// currently "foo"
funcs.makeCaps(); // Changes that same 'name'
funcs.inside(); // "FOO", because that 'name' has been changed
了解inside 和changer 都关闭在相同 上下文中很关键,这是创建它们的outside 调用的上下文。
了解每次调用 outside 都会创建新上下文和新函数也是关键:
var funcs1 = outside("foo");
var funcs2 = outside("separate");
funcs1.inside(); // "foo"
funcs2.inside(); // "separate"
funcs1.makeCaps();
funcs1.inside(); // "FOO"
funcs2.inside(); // "separate"