This is a simple script that’ll log the content of text from a Photoshop file.
var numOfLayers = app.activeDocument.layers.length;
var resultStr = "";
doAllLayers();
alert(resultStr);
function addToString(alayer)
{
if (alayer.kind == "LayerKind.TEXT")
{
var c = alayer.textItem.contents;
resultStr += c;
}
}
// main loop
function doAllLayers()
{
for (var i = numOfLayers -1; i >= 0; i--)
{
var thisLayer = app.activeDocument.layers[i];
addToString(thisLayer);
}
}
It works fine but I really should be passing a string into the function to add to itself, however it works.
How does the scope of JavaScript allow this to happen? Are declared local variables still accessed by functions or is it another trick I’m missing?
2
Answers
Here are some basic rules to variable scoping in JavaScript:
var
keyword, the variable is function-scoped. That is, the variable will be scoped to either the closest containing function, or to the global context if there is no containing function.Example:
let
keyword (ES6+), then the variable is block-scoped (this behavior more closely resembles most other C-family syntax languages). Example:var
orlet
keywords (e.g.,foo = bar
), then the variable is scoped to the global context. Example:In all of these cases, functions defined within scope of a variable still have access to the variable itself (technically you’re creating a closure, as the
numOfLayers
andresultStr
variables are lexically in scope of youraddToString
anddoAllLayers
functions).Please note that the scoping rules are technically a little more nuanced than this, but you’re better off reading a more in-depth article at that point.
You have defined
var resultStr = "";
outside function which is a global variable. you can access this global variable insideaddToString()
and start concatenating to it. Note that inside the method you have not declaredvar resultStr = "";
else it would have been a different variable local to that method.