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?
If you only want to fix the Bad Invocation problem you can do this:
By splitting the declaration and assignment you make your code easier to understand and to maintain. Another option is to declare a function with a name:
A slight reordering of your code will help.
or
JSLink is Crawford's personal opinion on how Javascript should be written. Most of it is excellent advice, but sometimes his opinion seems to get into the way.
This is the more "standard" way to write that line:
Note the whole (function ...) is inside the parens.
You should not assign a function reference and invoke the function at the same time. This kind of thing would easily cause heads to explode, as it would add to the already existing possibilities of assigning a variable to a reference, assigning a variable to a return, or assigning a variable to the result of an assignment. The way to do so anyone else would be able to read your code would be to do it in 2 lines. If you want to wrap that in a function it would be something like:
That by itself buys you nothing but obfuscation over doing it the simple way since the invocation wouldn't stick around regardless. You could however, if you really wanted create a function that does this:
and then
or if you were feeling even fancier and have JS gurus working with you, you could throw it on to the Function.prototype and chain it off the declaration. You can also pepper in call/apply to maintain the
this
reference and arguments (but it seems like that would just be noise for your present question).All of this should be done with extreme prudence it's certainly not worth going this route to save yourself having to type a couple extra lines of one command each.
If passing jslint is absolutely necessary then:
should do the job.
Edit
For passing params during
.call