提问人:Abhijeet 提问时间:9/16/2023 更新时间:9/16/2023 访问量:28
在JS中做范围和闭包[复制]
Doing scopes & closures in JS [duplicate]
问:
我写了一个范围和闭包的代码
function fun1(){
let a = 2
function fun2(){
console.log(a)
}
return fun2
}
b = fun1()
console.log(b)
根据我的说法,我在 b 变量中存储了 fun1 函数。fun1() 返回给我 fun2 方法,它应该执行控制台 .log(a) 即值 2....
但在这里它只给了我 [函数:fun2]
我错过了什么或没有做什么?
答:
-2赞
Alexander Nenashev
9/16/2023
#1
由于您从 fun1() 返回 fun2() 并在 的声明中调用 fun1(),因此在声明后是 fun2,因此您应该调用它来记录。
另请注意 fun2() 返回 undefined。因此,记录 b() 的输出可能是多余的:b
b
a
function fun1(){
let a = 2
function fun2(){
console.log(a)
}
return fun2
}
const b = fun1()
console.log(b())
评论
2赞
GrafiCode
9/16/2023
这里的问题不就是缺少括号吗?
评论
fun2
b