Simple analysis of return and closure functions in javascript

  • 2020-03-30 03:12:42
  • OfStack


Master bypass! This has nothing to do with the closure itself, and I don't know how to take the title, just a random number, please forgive me!

Today, a friend who just learned js gave me a piece of code to ask why the method is not executed. The code is as follows:


function makefunc(x) {
 return function (){
  return x;
 }
}
alert(makefunc(0));

It's not that it's not executed, it's just that it's a friend so alert should say "0" instead of function (){return x; }.
It's not that the script is wrong, it's just that the return, which exits from the current function, returns a value from that function. If you're returning a function, you're also returning the function itself.
You can modify the above code by saying alert(makefunc(0)()) :

function makefunc(x) {
 return (function (){
  return x;
 })();
}
alert(makefunc(0)());

If you want to return the result of the execution of the function, you should first make the function execute, for example:


function makefunc(x) {
 return (function (){
  return x;
 })();
}
alert(makefunc(0));

There's an anonymous function,

(function (){
 return x;
})();

Inside the first parenthesis is an anonymous function, and inside the second parenthesis, which is used to call the anonymous function, you pass in the required parameters. Such as:

(function( x , y){
 alert( x + y);
})(2 ,3 );


Related articles: