Copy link to clipboard
Copied
It seems the trend lately is to wrap code in a
(function() {...})();
construct where possible, where in the past a
main();
function main(){...}
construct was more common.
Is there any practical difference? Do both equally preserve global namespace?
The latter easily allows for an initial condition check, like
if (app.documents.length > 0 && app.selection.length > 0) {
main(app.selection[0]);
}
Is there any performance difference in just performing that check inside the IIFE?
Sorry if these have obvious answers. I'm starting to rely more and more on scripting to improve workflow, and would like to move the bar to writing better code, rather than just functional enough to get by.
Copy link to clipboard
Copied
Hi @davidt12412601 , For me it depends on whether I need to call the function multiple times. For example if I want to make new color swatches, I use a function for the swatch creation that checks if the swatch already exists in the document:
var d = app.activeDocument
var c = makeSwatch(d, "ProcessCyan")
c.properties = {model:ColorModel.PROCESS, space:ColorSpace.CMYK, colorValue:[100,0,0,0]}
var r = makeSwatch(d, "Red")
r.properties = {model:ColorModel.PROCESS, space:ColorSpace.CMYK, colorValue:[15,100,100,0]}
var g = makeSwatch(d, "Green")
g.properties = {model:ColorModel.PROCESS, space:ColorSpace.CMYK, colorValue:[100,0,100,0]}
/**
* Makes a new named Swatch
* @ param the document to add the color to
* @ param color name
* @ return the new swatch
*/
function makeSwatch(d, n){
if (d.colors.itemByName(n).isValid) {
return d.colors.itemByName(n);
} else {
return d.colors.add({name:n});
}
}
Copy link to clipboard
Copied
Thanks, rob. In this case, I was wondering about functions that are a wrapper for code that is only used once. But that's a good reminder to break out any repeated tasks into dedicated functions.
Copy link to clipboard
Copied
(function() {...})();
is called the Anonymous Function. Here is an explanation by Marc. (see section II).
Copy link to clipboard
Copied
Thanks for the link to that excellent explanation!
Copy link to clipboard
Copied
The practical difference is that an anonymous function is truly anonymous, whereas using a function main() and calling it adds that function to the global namespace.
In practice it doesn't make much difference.
Copy link to clipboard
Copied
Makes sense. So, if I'm using the 'main' targetengine, then the namespace is destroyed when the script ends so it doesn't matter. And if I'm using a persistent engine, the function main() would persist, but would likely be redefined in the next script before it's called again anyway if I'm using that pattern. Thanks!