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 is in effect the declaration (and definition) of such a variable. (That variable’s status, as we have already seen, is essentially the same as that of a property.) The variable’s name is the name of the handler, and its value is the handler’s bytecode, its functionality.

A handler may thus be referred to like any other variable, and you can get and set its value. For example:

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

In that example, we stored a handler as the value of a variable, and then called the variable as if it were a handler! This works because the variable is a handler.

The value of a handler can also be set. No law says you have to set it to another handler. For example, you could do this:

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

You can set one handler to the value of another, in effect substituting one entire functionality for another. Of course, the functionality has to be defined somewhere to begin with. For example:

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

Handlers as Parameters

At this point, you’re probably thinking: “Wow! If I can store a handler as a variable, I can pass it as a parameter to another handler!” ...

Get AppleScript: The Definitive Guide 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.