简体   繁体   English

JS:进行闭包时,如果我不存储为变量,内部函数如何访问外部函数参数?

[英]JS: When making a closure, how does the inner function access the outer function argument if I'm not storing as a variable?

I don't know how these closures 2 accomplish the same thing. 我不知道这些闭包2是如何完成同一件事的。 I understand how example 1 below would work since the variable foo is storing the value of the argument but what I can not understand is that taking away the variable in example 2 and just accessing the outer argument directly from the inner func, how does it have any reference to that? 我知道下面的示例1会如何工作,因为变量foo存储了参数的值,但是我不明白的是,在示例2中删除了变量,而直接从内部函数访问外部参数,它有什么作用有什么参考吗?

 //ex1: function firstex1(x) { let foo = x; console.log(foo) function second() { return foo + 100 } return second } console.log("Example 1: "+ firstex1(1)()); //ex:2 function firstex2(x) { console.log(x) function second() { return x + 100 } return second } console.log("Example 2: "+ firstex2(1)()); 

In example 2 a argument x is passed to the outer function. 在示例2中,参数x传递给外部函数。 Inside the outer function every entity has access to x as it's scope is covered in the full code block of that function. 在外部函数内部,每个实体都可以访问x,因为x的范围在该函数的完整代码块中涵盖。 When an inner function tries to access that x it can do it easily as it has access to that scope because it itself is present in that scope. 当内部函数尝试访问该x时,它可以轻松实现它,因为它可以访问该范围,因为它本身存在于该范围中。 It's just like when you declare a global variable and try to access it inside a function. 就像您声明全局变量并尝试在函数内部访问它一样。 The function has access to all the global variables. 该函数可以访问所有全局变量。

  var count=0; function a() { console.log(count++) } a(); 

The above will return count+1 and so will 上面将返回count + 1,因此将返回

  function first(x) { console.log(x) function second() { return x + 100 } return second } console.log(first(1)()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM