var hi = function(type) {
if (type == "boss") {
return function(name) {
alert("Hi chief " + name);
};
} else {
return function(name) {
alert("Hi " + name);
};
}
};
hi("boss"); // this will do nothing
var returnedFunction = hi();
returnedFunction("boss"); // prompt "Hi boss"
returnedFunction = hi("boss");
returnedFunction(); // prompt "Hi chief undefined"
returnedFunction("Douglas"); // prompt "Hi chief Douglas";
Ok so I understand pretty much everything that's going on except the first one:
hi("boss"); // this will do nothing
I would expect it to return "Hi chief undefined".
Doesn't the "boss" argument would mean it enters the if statement, where it should execute the function with argument name being undefined: hence you should get "Hi chief undefined".
Any information on how/why I get this behaviour would be most welcome. I am trying to understand and learn the basics of javascript !
Kind regards
It returns only function, it doesn't execute it. You would have to write:
hi("boss")(); // it would print Hi chief undefined
in order to execute it
You could probably say that
hi("boss");
is equaivelnt of writing
function(name) {
alert("Hi chief " + name);
};
While writing
hi("boss")();
is like wiring
function(name) {
alert("Hi chief " + name);
}(); // notiice the ()
hi("boss");
This line of code will return
function (name) {
alert("Hi chief " + name);
}
this function.
Now you have to execute it.
in order to execute it just write hi("boss")();
Why not just:
var hi = function(type, name) {
if (type == "boss") {
alert("Hi chief " + name);
} else {
alert("Hi " + name);
}
};
`
var hi = function(type) {
if (type == "boss") {
return function(name) {
alert("Hi chief " + name);
};
} else {
return function(name) {
alert("Hi " + name);
};
}
};
//return a function not excecuted
// hi();
// x is the returned function
var x = hi("boss");
x("name");
// 2
// hi("boss")("name");
`
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.