Javascript 闭包没有正确显示参数
Javascript closure not showing parameters properly
为了学习闭包,我玩了一下闭包,并编写了这段代码:
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");
我原以为它会打印出:"Hi, cat dog horse" 但它却打印出:"Hi, horse dog horse"
拜托,运行 在这里:
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");
是什么导致了这种行为?
谢谢。
尝试:
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");
注意:您的代码并不是真正的闭包 ;)
之前的响应将打印 "horse - dog - cat",但您想要 "cat - dog - horse"。
我想你想要的是:
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");
此外,这确实是一个闭包,因为链中的内部函数可以访问外部函数变量。最内部的函数,可以从外部函数访问 b 和 c 变量,但是你不能从内部函数范围之外访问这两个变量。
为了学习闭包,我玩了一下闭包,并编写了这段代码:
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");
我原以为它会打印出:"Hi, cat dog horse" 但它却打印出:"Hi, horse dog horse"
拜托,运行 在这里:
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");
是什么导致了这种行为?
谢谢。
尝试:
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");
注意:您的代码并不是真正的闭包 ;)
之前的响应将打印 "horse - dog - cat",但您想要 "cat - dog - horse"。
我想你想要的是:
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");
此外,这确实是一个闭包,因为链中的内部函数可以访问外部函数变量。最内部的函数,可以从外部函数访问 b 和 c 变量,但是你不能从内部函数范围之外访问这两个变量。