简体   繁体   中英

Can i call an anonymous function later on

I was working on a function in JavaScript and i wondered if i could call a anonymous function later on:

code
more code

(function() {
alert('Hello World!');
})();
more code
(function() {
alert('Goodbye World!');
})();

//call to the first anonymous function
//call to the first anonymous function 

Is it possible to call anonymous functions? I imagine there could be an array containing all functions?

Since functions are "first class citizens" you can assign them to variables, or put them into arrays/objects whatever just like any other var, whether they're anonymous or not.

So you'll have to assign the anonymous function to a variable (or put it into an array) in order to have some kind of means to reference it later on.

Furthermore, you don't execute it immediately, rather you execute it at a later time.

var anon1 = (function(){
    alert("anon1");
}); // <-- no () so it doesn't execute now.

// code code

anon1(); // <-- execute now

// ----- or -------
var myFuncs = [];

myFuncs.push( (function(){
    alert("in myFuncs");
}) ); // <-- not executing it here.

// code code

myFuncs[0](); // <-- execute now

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