我有这个代码:
function outside() {
var x = 10;
function inside(x) {
return x;
}
return inside;
}
result = outside()(20); // returns 20 instead of 10
为什么函数返回 20 而不是 10 以及为什么我不能用 outside (20) 而不是 outside ()(2) 调用 outdise 函数;为什么 ()?
我有这个代码:
function outside() {
var x = 10;
function inside(x) {
return x;
}
return inside;
}
result = outside()(20); // returns 20 instead of 10
为什么函数返回 20 而不是 10 以及为什么我不能用 outside (20) 而不是 outside ()(2) 调用 outdise 函数;为什么 ()?
这是一个非常“家庭作业”的问题,但是......
以下内容与您写的完全相同:
var inside = function (x) { return x }
var outside = function () {
var x = 10;
return inside;
}
单步执行函数调用:var result = outside()(20)
,我们看到这与
var result = outside(); // result == inside
result(20); // same as calling inside(20), which returns 20.
当您引用一个变量名时,JavaScript 将尝试从最本地的范围开始解析该引用。在这种情况下:
function outside() {
var x = 10; // This is the second most local
function inside(x) { // The x variable here is the most local
return x; // x will be the most local variable named x, ie the parameter
}
return inside;
}
你会得到你传递给inside()
函数的任何东西。现在,如果你有这个:
function outside() {
var x = 10; // This is now the most local
function inside(y) { // Renamed the parameter to y
return x; // returns the variable x
}
return inside;
}
然后你会得到 10,因为y
参数不再干扰函数中的x
变量outside()
。即使在函数通过称为闭包的机制退出后,的值x
也将保持不变。outside()
现在想象你有:
var x = 5; // This is a global variable
function outside() {
var x = 10; // This is the most local
function inside(y) {
return x; // x here will refer to the x with a value of 10
}
return inside;
}
在这种情况下,您也会得到 10,因为函数x
内部的变量比全局变量更局部。outside()
x
至于你的函数调用:
result = outside()(20);
表达式outside()
正在调用函数outside
,该函数返回对函数的引用inside()
:
return inside; // Inside is a function, we're not calling it because there are no parens
然后你调用那个你有引用的函数(即inside
函数)并传入参数值 20。如果双括号令人困惑,你可以这样想:
var foo = outside(); // foo is a reference to a function
result = foo(20); // We're now calling that function, passing in 20 as the parameter
您的inside()
函数返回 的值20
,该值设置为变量result
。
为什么函数返回 20 而不是 10
当存在命名冲突时,内部范围优先。
为什么我不能用 outside (20) 而不是 outside ()(2) 调用 outdise 函数;为什么 ()?
调用outside()
会返回一个函数(从 中可以看出return inner
)。然后调用该函数。如果你要调用outside(20)
它,它仍然会返回内部函数。如果你扩展它,它可能会更清楚:
var outResult = outside(); // outside returns `inner`, the variable now contains that function
outResult(20); // call the inner function passing the value 20