Creating a Function
If you are new to scripting for Photoshop, please view our Photoshop
Scripting Basics tutorial for an introduction to Photoshop scripting and a few exercises
about basic JavaScript.
Functions are a great way to keep large and complicated lines of code organized.
1. Type in the function keyword.
function
|
|
2. Enter the name for your Function followed by parentheses
( ). This name will be used everytime you want to tell your scirpt to run the function.
function myFunction()
|
|
3. Create an opening brace and closing brace {}. The
brace will hold the code that will be run when you call myFunction().
function myFunction() {
}
|
|
4. Type in the code between the braces {};.
function myFunction() {
alert("This is a function");
}
|
|
5. Now everytime we want to use the alert, you can
simply type in myFunction() instead. Run the script in Photoshop (File> Script> Browse) to
ensure that it is working.
function myFunction() {
alert("This is a function");
}
myFunction();
|
Adding Parameters to a Function
You may also pass paramaters to functions making them more useful.
1. First type in the function code:
function sum() {
}
|
|
2. Type in the variables you would like to set inside
the brackets. Seperate the variables by a comma.
function sum(myVar, myVar2, myVar3) {
}
|
|
3. Lets type an alert function to test the variables.
function sum(myVar, myVar2, myVar3) {
alert(a + b + c) ;
}
|
|
4. Call the function with the values of the variables
inside the parenthesis ( ).
function sum(myVar, myVar2, myVar3) {
alert(myVar + myVar2 + myVar3) ;
}
sum(4, 6, 8)
|
|
| 5. Save and run the script inside Photoshop (File> Scripts> Browse).
A pop-up should appear with the sum of 4 + 6 + 8. |