Script Objects

Script objects give AppleScript very basic object-oriented features, including inheritance. A script object is defined in a script-code block that looks a little like a subroutine definition. Script objects are created within a script with the script [script name]...end script syntax. Example 1-17 contains a simple script object definition. The object has two methods: one returns a property value and the other method increments the value of the property by one. The bottom of the script creates two copies of this object then calls its methods and displays the results.

Example 1-17. Creating a Script Object
(* begin the script object definition *)
script Test
   property myval : 0 -- one integer property
   on getVal(  ) -- define a method
      return myval -- return the prop value
   end getVal
   on upVal(  ) -- define another method
      set myval to myval + 1 -- increment myval property  by one
   end upVal
end script -- end script object definition
copy Test to t1 -- create new Test object
copy Test to t2 -- create another, different Test object
(* two ways to call an object's methods *)
tell t1 to upVal(  )
t2's upVal(  )
t2's upVal(  ) (* t2's upVal method is called twice, setting its myval property
to 2 *)
set theMessage to "t1: " & (t1's getVal(  ) as string) (* find out the two
object's property values *)
set theMessage to theMessage & return & "t2: " & (t2's getVal(  ) 
as string)
display dialog theMessage

You may have noticed the use of the keyword copy to create the two Test objects in ...

Get AppleScript in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.