[英]Javascript closure not showing parameters properly
I was playing a bit with closures in order to learn them, and made this code:为了学习它们,我玩了一些闭包,并编写了以下代码:
function showName(a,b,c){
(function nombresAnidados(a){
(function(b){
(function(c){
console.log("hola " + a + " " + b + " " + c);
})(a)
})(b)
})(c)
}
showName("cat","dog","horse");
I was expecting it to print out: "Hi, cat dog horse" but instead it prints: "Hi, horse dog horse"我期待它打印出:“嗨,猫狗马”,但它打印出:“嗨,马狗马”
Please, run it here:请在这里运行它:
function showName(a,b,c){ (function nombresAnidados(a){ (function(b){ (function(c){ console.log("Hi, " + a + " " + b + " " + c); })(a) })(b) })(c) } showName("cat","dog","horse");
What causes this behavior?是什么导致了这种行为?
Thanks.谢谢。
try:尝试:
function showName(a, b, c) { (function nombresAnidados(x) // here your arg a get the value of c { (function (y) { (function (z) { console.log( `hi: ${x} - ${y} - ${z}` ); })(a) // --> z (cat) })(b) // --> y (dog) })(c) // --> x (horse) } showName("cat", "dog", "horse");
note: your code is not really a closure;)注意:您的代码并不是真正的闭包;)
The previous response will print "horse - dog - cat", but you wanted "cat - dog - horse".先前的响应将打印“马 - 狗 - 猫”,但您想要“猫 - 狗 - 马”。
What I think you want is this:我想你想要的是这样的:
function showName(a, b, c)
{
(function nombresAnidados(c)
{
(function (b)
{
(function (a)
{
console.log( `hi : ${a} - ${b} - ${c}` );
})(a) // a (cat)
})(b) // b (dog)
})(c) // c (horse)
}
showName("cat", "dog", "horse");
Also, this is indeed a Closure as the inner functions in the chain has access to the outer functions variables.此外,这确实是一个闭包,因为链中的内部函数可以访问外部函数变量。 The most inner function, can access b and c variables from the outer functions, but you can't access both of those variables from outside that inner function scope.
The most inner function, can access b and c variables from the outer functions, but you can't access both of those variables from outside that inner function scope.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.