I have quite a few of these:
function addEventsAndStuff() { // bla bla } addEventsAndStuff(); function sendStuffToServer() { // send stuff // get HTML in response // replace DOM // add events: addEventsAndStuff(); }
Re-adding the events is necessary because the DOM has changed, so previously attached events are gone. Since they have to be attached initially as well (duh), they're in a nice function to be DRY.
There's nothing wrong with this set up (or is there?), but can I smooth it a little bit? I'd like to create the addEventsAndStuff()
function and immediately call it, so it doesn't look so amateuristic.
Both following respond with a syntax error:
function addEventsAndStuff() { alert('oele'); }(); (function addEventsAndStuff() { alert('oele'); })();
Any takers?
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog. (function () { // … }) (); (() => { // … })
So generally html - including javascript - has a top down method of parsing code. However, functions go out of this route as they are read first, but only the function head (= first line). That is why function calls are possible before declaration.
The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
Javascript functions are only executed when you explicitly call them (or implicitly in callbacks and whatnot). The code will however still be interpreted by the browser on each page regardless of functions being called or not.
There's nothing wrong with the example you posted in your question.. The other way of doing it may look odd, but:
var addEventsAndStuff; (addEventsAndStuff = function(){ // add events, and ... stuff })();
There are two ways to define a function in JavaScript. A function declaration:
function foo(){ ... }
and a function expression, which is any way of defining a function other than the above:
var foo = function(){}; (function(){})(); var foo = {bar : function(){}};
...etc
function expressions can be named, but their name is not propagated to the containing scope. Meaning this code is valid:
(function foo(){ foo(); // recursion for some reason }());
but this isn't:
(function foo(){ ... }()); foo(); // foo does not exist
So in order to name your function and immediately call it, you need to define a local variable, assign your function to it as an expression, then call it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With