Experts take a detour! This has nothing to do with the closure itself, and I don’t know how to get the title, so I just collected the number. I hope I’ll forgive me!
Today, a friend who just learned js gave me a piece of code and asked me why the method was not executed. The code is as follows:
The code copy is as follows:
function makefunc(x) {
return function (){
return x;
}
}
alert(makefunc(0));
In fact, it is not that it is not that it does not execute, but that the friend means that the alert should be "0", not function (){return x;}.
It's not that the script is written wrong, it's just that it doesn't understand the return, exits from the current function, and returns a value from that function. If the returned function is a function, then the returned function itself is also the function itself.
You can modify the above code like this, which is alert(makefunc(0)()):
The code copy is as follows:
function makefunc(x) {
return (function (){
return x;
})();
}
alert(makefunc(0)());
If you want to return the result of the function execution, then you must first let the function execute, for example:
The code copy is as follows:
function makefunc(x) {
return (function (){
return x;
})();
}
alert(makefunc(0));
Here is an anonymous function.
The code copy is as follows:
(function (){
return x;
})();
Inside the first bracket is an anonymous function, the second bracket is used to call the anonymous function, and you can pass in the required parameters in the second bracket. For example:
The code copy is as follows:
(function( x , y){
alert( x + y);
})(twenty three );