简体   繁体   中英

Return a Function within a Function

Here is an example of code I am experimenting with:

var hello = function hi(){
    function bye(){
        console.log(hi);
        return hi;
    }
    bye();
};

hello();

Here is a repl.it link

I am trying to return the function hi from my function bye . As you can see, when I console.log(hi) the value appears to present, but my return statement doesn't return the hi function. Why isn't the return statement returning the reference to hi ?

你忘了return再见。

return bye();

Don't make think complicated by defining a function inside another one

Define your hi function first like this for example

function hi (message) 
{ 
     console.log(message) 
}

it takes an argument and show it on the console

now let's define our bye function

function bye ()
{
     hi(" Called from the function bye ");
}

no when you call bye , you call hi at the same time

bye(); // it will show on the console the message " Called from ... " 

If you want to return a function from a function it's easy you define your hi function like this

function hi (message) 
{ 
     console.log(message) 
}

and the bye function returns the hi function like this

function bye() 
{
     return hi;
}

All you need to do now, is to call the bye function and give the argument to show in the console to what was returned , just like this

bye()(" This is a sample message "); 

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