【问题标题】:How JS Scope / Closures is Passing ArgumentJS 作用域/闭包如何传递参数
【发布时间】:2017-03-15 01:43:33
【问题描述】:
有人能解释一下为什么在下面的函数中,我可以将参数传递给嵌套函数吗?我的理解是它必须与闭包和作用域有关(我认为我对此有很好的理解),但我似乎可以理解这个论点是如何传递的。
下面的函数分别输出 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);
【问题讨论】:
标签:
javascript
scope
closures
【解决方案1】:
函数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) 时,您实际上是在使用参数 2 调用 doThis(),它成为 a 的值。
这是一个稍微简化的版本。为了对此进行扩展,doSomething() 函数被描述为 关闭 doThis() 创建一个 closure。相反,函数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() 的输出。闭包可防止代码 inside 从闭包 outside 访问。
【解决方案2】:
分配var exec = doSomething();的时候,exec基本上就是在写:
var doSomething = function(a) {
console.log(b);
console.log(a);
}
它变成了它自己的功能。所以传入2 就像exec(2) 一样工作,除了它有变量b 因为闭包可用。