gpt4 book ai didi

javascript - 在此嵌套函数示例中如何传递值

转载 作者:行者123 更新时间:2023-11-29 20:57:23 25 4
gpt4 key购买 nike

从这里学习 Javascript - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

我明白这几点

  1. 您可以在一个函数中嵌套一个函数
  2. 只能从外部的语句访问内部函数功能。 [嵌套(内部)函数对其包含的函数是私有(private)的(外)功能。它还形成一个闭包]
  3. 内部函数形成一个闭包:内部函数可以使用外部函数的参数和变量,而外部函数不能使用内部的参数和变量功能。

但是我不明白第二个值实际上是如何一直传递到内部函数的,就像它作为参数传递给内部函数一样?

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
*/

编辑-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
*/

编辑-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。这样做是因为:

  1. B 形成一个包含 A 的闭包,即 B 可以访问 A 的参数并且变量。
  2. C 形成一个包含 B 的闭包。
  3. 因为B的闭包包含A,C的闭包包含A,C可以访问B 和 A 的参数和变量。换句话说,C链B 和 A 的范围。

然而,反之则不然。

  • A 不能访问 C,因为 A 不能访问任何参数或变量B 的,其中 C 是 B 的变量。因此,C 仅对 B 保持私有(private)。

最佳答案

outside(someValue) 调用的结果是一个函数。因此,要调用结果(内部)函数,您需要调用 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)

关于javascript - 在此嵌套函数示例中如何传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com