Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concisely assign and immediately invoke a function variable?

The following is a method for defining an anonymous function within a closure, invoke the function, and forget it:

(function () { "do stuff"; })();

This is used to maintain a limited scope without adding bulk to the script (IIFE: Immediately-Invoked Function Expression).

What if you're hoping to immediately execute a function, while still retaining the function for future use, like the following:

var doThing;
(doThing = function () { "do stuff"; })();

This works in the browsers I've tested (Chrome, FF, IE8, IE10), but this does not pass JSLint (Bad Invocation). Are there any compatibility issues with doing it this way?

Is there a way of accomplishing this that is looked kindly upon by JSLint?

like image 836
Aejay Avatar asked Sep 10 '12 20:09

Aejay


People also ask

What is the use of immediately invoked function expression?

Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

Does declared function execute immediately?

Function expressions are evaluated during execution. So you can't execute function declarations immediately because even variables don't exist yet and other code that the function might depend on hasn't been executed either.

What is an immediately invoked function in JavaScript explain with suitable example?

An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.

How do you call a function assigned to a variable in JavaScript?

Users can follow the below syntax to write the expression for the arrow function. const variable = ( … parameters ) => { // function body } Variable( parameters ); // invoke the arrow function. In the above syntax, users can see how we declared the arrow function expression without using the function keyword.


1 Answers

If passing jslint is absolutely necessary then:

var doThing;
(doThing = function () { "do stuff"; }).call();

should do the job.

Edit

For passing params during .call

var doThing;
(doThing = function (param1, param2) { 'do stuff'; }).call(this, arg1, arg2);
like image 171
Cristian Sanchez Avatar answered Sep 24 '22 10:09

Cristian Sanchez