
C
HAPTER
5: Scripting with JavaScript
Accessing and referencing objects
42
Accessing and referencing objects
When you write a script, you must first decide which file, or
document
, the script should act on. Through
the
application
object, the script can create a new document, open an existing document, or act on a
document that is already open.
The script can create new objects in the document, operate on objects that the user selected, or operate
on objects in one of the object collections. The following sections illustrate various techniques for
accessing, referencing, and manipulating Illustrator objects.
Referencing the application object
To obtain a reference to a specific object, you need to navigate the containment hierarchy. Because all
JavaScript scripts are executed from within the Illustrator application, however, a specific reference to the
application
object is not required. For example, to assign the active document in Illustrator to the
variable
frontMostDocument
, you could reference the
activeDocument
property of the
application
object, as follows:
var frontMostDocument = activeDocument;
It is permissible to use the
application
object in a reference. To reference the
application
object, use
the
app
global variable. The following two statements appear identical to the JavaScript engine:
var frontMostDocument = activeDocument;
var frontMostDocument = app.activeDocument;
Accessing objects in collections
All open documents, as well as the objects in a document, are collected into collection objects for the
object type. A collection object contains an array of the objects that you can access by index or name. The
collection object takes the plural form of the object name. For example, the collection object for the
document
object is
documents
.
The following script sample gets all
graphic
style
objects in the
graphic
styles
collection; that is, it
gets all graphic styles available to the active document:
var myStyles = app.activeDocument.graphicStyles;
All numeric collection references in JavaScript are zero-based: the first object in the collection has the
index [0].
As a rule, JavaScript index numbers do not shift when you add an object to a collection. There is one
exception:
documents[0]
is always the active or frontmost document.
To access the first style in a
graphic
styles
collection, you can use the variable declared in the previous
script sample, or you can use the containment hierarchy to refer to the collection:
➤
Using the
myStyles
variable:
var firstStyle = myStyles[0];
➤
Using the containment hierarchy:
var firstStyle = app.activeDocument.graphicStyles[0];