我认为你在理解 JS 中的函数、变量和参数如何工作方面存在一个基本问题。我将解释您的代码,希望能启发您:
function outside() {
var x = 10; // variable x is a local variable in the scope of the outside function. it is not used anywhere
function inside(x) {
// parameter x hides the variable in the outer scope (outside) with the same name
// this function returns the first parameter passed to it.
// what the value returned is will be decided when the function is called
return x;
}
function inside2(a) {
// this function also returns the first parameter passed to it.
return a;
}
return inside2; // or inside, doesn't seem to make a difference here
// no difference because both functions do the same thing
}
outside()(20,5) // this code is equivalent to the following lines:
var temp = outside(); // temp is the return value of outside - in our case the inside2 function
temp(20,5); // the inside2 function is called with 2 arguments. It returns the first one (20) and ignores the other one
如果你想更好地解释你想用你的代码实现什么,请这样做,我会帮助你做到这一点。同时,一些来自 MDN 的函数和范围的阅读:
https ://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope
编辑:经过一番猜测,我想也许你可能想做这样的事情:
function outside(x,a) {
function inside1() {
return x; // returns the x from the outer scope = the first parameter passed to outside
}
function inside2() {
return a; // returns the a from the outer scope = the second parameter passed to outside
}
return inside2;
}
outside(20,5)() // returns 5
一个 JsBin,所以你可以摆弄它:http: //jsbin.com/oKAroQI/1/edit