gpt4 book ai didi

javascript - JS 作用域/闭包如何传递参数

转载 作者:行者123 更新时间:2023-11-30 08:29:17 26 4
gpt4 key购买 nike

有人可以解释为什么在下面的函数中,我可以将参数传递给嵌套函数吗?我的理解是它必须对闭包和作用域做一些事情(我认为我对此有很好的理解),但我似乎可以理解这个论点是如何被传递的。

下面的函数分别输出1,2。但是返回语句 doThis() 是如何得到“a”的参数的呢?我不知道这是在哪里/如何访问/传递的。

function doSomething(){
var b = 1;
return function doThis(a){
console.log(b);//1
console.log(a);//2
}
}
var exec = doSomething();
exec(2);

最佳答案

函数 doSomething() 返回另一个函数,所以当你执行时

var exec = doSomething();

你可以认为 exec 包含以下函数

function doThis(a){ // <- takes an argument
console.log(1); // comes from the b argument in the outer scope
console.log(a); // not set yet
}

因此,当您调用 exec(2) 时,您实际上是在调用带有参数 2doThis(),它成为 的值>一个

这是一个稍微简化的版本。为了对此进行扩展,doSomething() 函数被描述为关闭 doThis() 创建一个闭包。相反,doThis() 函数关闭在闭包内。闭包本身只是函数的一个有限状态:

function doSomething(){ // --> defines the closure
var b = 1; // variable only visible within doSomething()
return function doThis(a){ //<--> function has access to everything in doSomething(). Also defines another closure
console.log(b); // --> accesses the OUTER scope
console.log(a); // <-- comes from the INNER scope
} // <-- end INNER scope
} // --> end OUTER scope

当您执行 doSomething() 时,返回的结果仍然保留对其范围内的访问权限,这就是为什么 doThis() 可以访问值 b - 它很容易到达。这与您的操作方式类似

var foo = 40;

function bar(value) {
return foo + value;
}

console.log(bar(2));

只有在这种情况下,任何其他代码都可以访问 foo,因为它是一个全局变量,所以如果您在不同的函数中执行 foo = 100,那将会改变bar() 的输出。闭包阻止内部 的代码可以从外部 闭包访问。

关于javascript - JS 作用域/闭包如何传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40368197/

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