How can I tell closure compiler that an anonymous function should not be removed as dead code? I do not want to store the function to the window object. I am looking for an alternative technique.
Say I have a javascript file that contains one giant anonymous function.
(function(){return "I am here!"})
For usage, I download this function via ajax and then capture the output of eval using something like
var f = eval('(function(){return "I am here!"})');
This assigns the anonymous function in the variable f.
d8> var f = eval('(function(){return "I am here!"})');
d8> f
function (){return "I am here!"}
d8> f()
I am here!
When I run the compiler over my js file that contains a single large anonymous function, the compiler “optimizes” my code by outputting nothing. This is obviously not what I want. Is there some sort of JSDoc I can put above my function to mark is as not being dead code?
~~~~~~~~~~~~~~~~~~~~~~~~
Work around: (This isn’t really what I wanted, but it seems to be the best result with the tools available)
~~~~~~~~~~~~~~~~~~~~~~~~
I ended up using a combination of John and David’s answers:
// code would be provided from an ajax request
var code = 'function F(){return "I am here!"};'
code = "("+code.replace(/\s*\;\s*$/, "")+");"
f = eval(code);
Giving the function a name makes the Closure Compiler happy.
Depending on the function, closure compiler will define variables outside of the function so I wrap the code in parenthesis to avoid defining global variables.
The replace method just moves the last semicolon used to separate the function definition so that it doesn’t cause a syntax error.
You could store the function in the file without the wrapper, which would prevent the compiler from ‘optimising’ it, and then add the function wrapper when you eval it.
If your code really is ‘invalid’ without the function wrapper, you could leave it wrapped, but execute the wrapper, then continue as above. For example: