Initializing Script Objects
When you define a script object, you define a collection of handlers and properties. When you run a script containing a script object definition, AppleScript creates a script object with the properties and handlers listed
in the definition. This is called initializing a script object. A script object
must be initialized before it can respond to commands.If you include a script object definition at the top level of a script--that is, as part of the script's Run handler--AppleScript initializes the script object each time the script's Run handler is executed. (For more information about Run handlers, see page 243.)
Similarly, if you include a script definition in another handler within a script, AppleScript initializes a script object each time the handler is called. The parameter variables in the handler definition become local variables of the script object. For example, the
makePoint
handler in the following script contains a script object definition for the script objectpoint
:
on makePoint(x, y) script point property xCoordinate:x property yCoordinate:y end script return point end makePoint set myPoint to makePoint(10,20) get xCoordinate of myPoint get yCoordinate of myPointAppleScript initializes the script objectpoint
when it executes themakePoint
command. The parameter variables in themakePoint
handler, in this case,x
andy
, become local variables of the script objectpoint
. The initial value ofx
is 10, and the initial value ofy
is 20, because those are the parameters of themakePoint
command that initialized the script object.One way to use script object definitions in handlers is to define constructor functions, that is, handlers that create script objects. The following script uses
a constructor function to create three script objects.
on makePoint(x, y) script property xCoordinate:x property yCoordinate:y end script end makePoint set PointA to makePoint(10,20) set PointB to makePoint(100,200) set PointC to makePoint(1,1)As in the previous example, you can retrieve the coordinates of the three script objects using the Get command.
- Note
- The distinction between defining a script object and initializing a script object is similar to the distinction between a class and an instance in object-oriented design. When you define a script object, you define a class of objects that respond to the same commands. When AppleScript initializes a script object, it creates an instance of the class. The script object gets its initial context (property values and handlers) from the script object definition, but its context can change as it responds to commands.
![]()