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?
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.
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.
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.
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.
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);
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