简体   繁体   中英

Calling Javascript function returns a function with undefined values

I have been recently learning JavaScript and came across this piece of code.

function sayIntro(name,age){

var address = "TX";

return function(name,age,address){
console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};

}

sayIntro("john",27)();

As per my understanding, the results are undefined because within the scope of returning function previous variables are not available. Still how do I get the output as bellow?

I am john
I am 27
from TX 

The parameters from the inner function shadows the outer function parameters and the variable. You can just access the variables inside the inner function, because when it tries to find a variable, it goes from its scope, if not found goes to the outer scope, in this case the outer function's scope and finds them.

But if you declare parameters in the inner function, they are founded and because you does not pass a value for them, their values are undefined . So you get undefined .

Or remove them from the inner function

return function() {
   console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};

or just remove the address and call the inner function and pass to it the parameters.

return function(name, age) {
   console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};

...

sayIntro()("john",27);

Example

 function sayIntro(name,age){ var address = "TX"; return function(){ console.log("I am "+ name + " \\nI am "+ age + " \\nfrom "+address); }; } sayIntro("john",27)(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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