Search code examples
javascriptfunctionjslintiife

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?


Solution

  • 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);