Handlers as Values

A handler is a datatype in AppleScript. This means that a variable's value can be a handler. In fact, a handler definition defines exactly such a variable. You can refer to this variable, and get and set its value, just as you would any other variable. Here, we fetch a handler as a value and assign it to another variable:

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
set sayHello to sayHowdy
sayHello( ) -- Howdy

As the example shows, after the assignment of the handler to another variable, we can call that variable as if it were a handler. That's because the variable is a handler.

You can also assign a new value to a variable whose value is a handler. No law says that this new value must be another handler; you're just replacing the value of the variable, as with any other variable. The original handler functionality is lost. For example, you could do this if you wanted:

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
set sayHowdy to 9
display dialog sayHowdy -- 9

You can assign to a variable whose value is a handler the value of another handler, in effect replacing its functionality with new functionality. Of course, that functionality has to be defined somewhere to begin with, and the old functionality is lost. For example:

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
on sayGetLost( )
    display dialog "Get Lost"
end sayGetLost
set sayHello to sayGetLost
sayHello( ) -- Get Lost

An elegant use of this feature is a list that acts as a dispatch table . The ...

Get AppleScript: The Definitive Guide, 2nd Edition 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.