12.4. Script Objects Containing Handlers

Your script objects can contain their own handler definitions. Like properties, those handlers are defined at the time you define the script. You can call the handlers directly from within the script object or from outside the script by using the notation handler of script (or the equivalent script's handler). In fact, that's what you did in Chapter 8 when you used the load script command to load your list handlers.

When you think of your program at the topmost level as a script object, you understand the idea of defining a handler inside a script. But in the next Try It Out, you explicitly create a script object and define three handlers inside that script object.

12.4.1.

12.4.1.1. Try It Out: Defining Handlers inside Scripts

In this program, you define three handlers inside a script.

  1. Type the following program into Script Editor:

    -- Handlers inside script objects
    
    script circle
        on area given radius:r
            return pi * r * r
        end area
    
        on circumference given radius:r
            return 2 * pi * r
        end circumference
    
        on volume given radius:r   -- okay, so it's a sphere
            return 4 * pi * (r ^ 3) / 3
        end volume
    end script
    
    -- now calculate and log various values
    
    log (area of circle given radius:5)
    log (circle's circumference given radius:10)  -- gets changed when compiled
    
    tell circle
        log (volume given radius:2)
    end tell
  2. Click the Event Log tab and run the program. You should see this output:

    (*78.539816339745*)
    (*62.831853071796*)
    (*33.510321638291*)
12.4.1.2. How ...

Get Beginning AppleScript® 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.