Executing a named function after its declaration

I know this can be done for anonymous functions

(function toBeExecutedImmediately() { // Code }()); 

I have a function that I want to use in other places, but should also be executed immediately. Is it possible to do this with one operator instead of the next ? Return value is not required.

 function toBeExecutedImmediately() { // Code }; toBeExecutedImmediately(); 
+6
source share
3 answers

Is it possible to do this with one operator instead of the next?

No. As you already found, an expression with the name of the function (your first example) does not add the name to the content area (except for broken engines I look at you, IE8 and earlier), so you cannot call the function elsewhere without doing something, to make this possible, and, of course, with a function declaration (your second example), you must give twice.

Best of all, probably just go ahead and make an announcement and a separate call (your second example).

We could probably come up with something confusing that technically fits the definition of “one statement”, but is unlikely to be shorter.

If brevity is your goal, these are two statements, but brief:

 var f = function() { // Code }, toBeExecutedImmediately = f; f(); 

But although relatively short, I would say that clarity suffers. :-)

Of course, anything is possible if you add a helper function. For instance:

 // The helper function defineAndExecute(f) { f(); return f; } // using it var toBeExecutedImmediately = defineAndExecute(function() { // Do work here }); 

The function is technically anonymous, but you can call it through var . (Here you could use a named expression of the function, but of course it could defeat the goal of not repeating the name, as I understand it.)


Side note. Your first example is not an “anonymous function”. A function has its own name; it is a named function expression. It's just that with named function expressions, unlike function declarations, this name is not added to the content area.

+4
source

You can use the namespace:

 // alerts "say yes" (window.say = function (s) { alert('say ' + s); })('yes'); // alerts "say something" say('something'); 

As a response to comments, here's how to make a local function:

 (function(){ var dontSay; // alerts "don't say no" (dontSay = function (s) { alert('don\'t say ' + s); })('no'); // alerts "don't say anything" dontSay('anything'); })(); 

@JoeSimmons This is not a revolution, but the question is also not very important, D

+2
source

You can write a "constructor of functions" as follows:

 function DeclareAndExecute(name, func) { window[name] = func; func(); } 

Using:

 DeclareAndExecute("toBeExecutedImmediately", function() { //code here }); 

Live test .

This will add the function to the global scope window using the given name and insta-execute.

+1
source

Source: https://habr.com/ru/post/957279/


All Articles