从这里学习Javascript - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
我理解这些要点
但是我无法理解第二个值如何实际进入内部函数 - 如果它作为参数传递给内部函数?
function outside(y) {
console.log('y is ' + y);
function inside(x) {
console.log('x is ' + x);
return x+y;
}
return inside;
}
var a = outside(3);
//console.log(a); // this is easy to understand
/* output:
y is 3
ƒ inside(x) {
console.log('x is ' + x);
return x+y;
}
*/
var b = a(2); // Not able to clearly understand how 2 is interpreted as parameter to nested function.
// Is this bcoz a function was returned earlier and now we passed 2 to that function??
console.log(b);
/* output
y is 3
x is 2
5
*/
console.log('--------------');
var c = outside(3)(2); // How is 3 passed as outer function paramter and 2 passed as inner function parameter?
console.log('---------');
console.log(c);
/* output
y is 3
x is 2
5
--------------
y is 3
x is 2
---------
5
*/
EDIT-1:
非常感谢所有帮助过的人,理解了这些概念并写下了符合预期的工作。
function outside(y) {
console.log('y is ' + y);
function inside(x) {
console.log('x is ' + x);
function innermost(z) {
console.log('z is ' + z);
return x+y+z;
}
return innermost;
}
return inside;
}
outside(3)(2)(1);
/* output
y is 3
x is 2
z is 1
6
*/
EDIT-2:
另一种编写函数的方法,以满足EDIT-1中提到的上述目标。
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // logs 6 (1 + 2 + 3)
在这个例子中,C访问B的y和A的x。这可以做到,因为:
答案 0 :(得分:3)
outside(someValue)
来电的结果是function
。因此,要调用结果(内部)函数,您需要调用outside
函数两次。一次获取内部函数outside(3)
并再次将其称为outside(3)(4)
。
let innerFunc = outside(3) // here you get the inside function as result
innerFunc(4) // call it
与...相同:
outside(3)(4)
更多信息:
outside(3) // this calls the outside function and returns the inside function
outside(3)(4) // this calls the outside function returns the inside
//function as result of first call and calls the inside function with (4)
答案 1 :(得分:-1)
很多像这样,我会假设。
function outside(y) {
console.log('y is ' + y);
function inside(x) {
console.log('x is ' + x);
function inide(z) {
console.log('z is ' + z);
return y+z;
}
return x+y, inide;
}
return inside;
}
outside(3)(2)(1);