简体   繁体   中英

how to return anonymous function in javascript

<html>
    <head>
        <script>
             function test(){                   
                 return function(){
                  alert("hi");
                }                
             }
             test();
        </script>
    </head>
    <body>
    </body>
</html>

This is my code, can I ask why it doesnt work properly??

Because you're returning your function but not invoking it. Try this:

test()();

Here is a fiddle

I think you might be confused. test() returns a function reference, but it won't execute it.

You could do something like this

var alertFunc = test(); // return function reference
alertFunc(); // call the function

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