Immediate Function Invocation Syntax

Immediate function invocation syntax

From Douglass Crockford's style convention guide: (search for "invoked immediately")

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself.

updated reference, old PPT no longer exists

What is the (function() { } )() construct in JavaScript?

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).

Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa:

The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.

Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :

((foo) => {
// do something with foo here foo
})('foo value')

How to write an immediate function invocation in Java? JavaScript example provided

I am not java programmer but seems that something like this do the trick:

import java.util.concurrent.Callable;
import java.lang.String;

class LambdaTest {
public LambdaTest() {
boolean isFlag = true;
Callable<String> name = () -> {
if (isFlag) return "A";
else return "B";
};
try {
System.out.println(name.call());
} catch (Exception e) {
//cause call can throw exception so we need to handle that
}
}
public static void main(String... args) {
LambdaTest lt = new LambdaTest();
}
}

Immediate function using JavaScript ES6 arrow functions

From the Arrow functions examples,

(() => "foobar")() // returns "foobar" 

So, the function invocation operator should be outside.

(() => {
//...
})();

Sample: http://www.es6fiddle.net/hsb8s1sj/

Javascript immediate function invocation

You're actually immediately invoking both alerts. To get the expected behavior, you need to pass function references to the methods, not already-invoked functions (your IIFE is fine, it's your method declarations that are the cause of your problem):

var app = function () {
var ans = {
power: function() { alert("power") },
wow: function() { alert("wow") }
}
return ans;
}();

See the updated jsfiddle.

You can also, alternatively, take advantage of the fact that Function.prototype.bind returns a function reference:

var app = function () {
var ans = {
power: alert.bind(this, 'power'),
wow: alert.bind(this, 'wow')
}
return ans;
}();

app.power();

Here's that jsfiddle.

In your original code, if you open up your console, you'll see Uncaught TypeError: app.power is not a function. That's because window.alert returns undefined, and the window.alert functions were already invoked... therefore, they return undefined, and when you try to call app.power(), you're trying to invoke the return value of that method... and obviously undefined isn't a function, as the error very semantically states.

JavaScript anonymous function immediate invocation/execution (expression vs. declaration)

The first two cases show function expressions, and can appear anywhere an expression like (1+1 or x*f(4)) would appear. Just like how 1+1, evaluates to 2, these expressions evaluate to a corresponding function.


The third case is a function declation statement, and can appear anywhere you can have other statements (like an if or while statement).

There is not much point in trying to declare an anonymous function via a Funcion declaration statements, since otherwise noone would get a reference to the function afterwards.


The reason you need the opening ( or the var x = like in the first two cases is that they force next bit to be parsed in an expression context. (just think how you cant do var x = if ..., for example). If you just put the function as the first thing it will be parsed as the declaration statement you don't want.

Immediately invoked function expression without using grouping operator

In your code you don't have name for the function that's the reason for syntax error. Even if you would had name it would have thrown error.

function func(){  console.log('x')}();

Javascript Syntax: Immediately Invoked Function Expression (IIFE) with parameters

function($){
//other code here
}

This block is passed as a parameter to the outer IIFE. It might be clearer to write it like this:

var factoryDef = function($) { ... };

(function(factory) {
// this is the outer IIFE
var someVar = {};
// you can call:
factory(someVar);
// the previous line calls factoryDef with param someVar
}(factoryDef));

So factory(someVar) is the same as factoryDef({}); the latter is simply the value of factory (which is the function factoryDef) called with the value of someVar (which is {}.)

Does that make sense?



Related Topics



Leave a reply



Submit