Is there a way to mimic classes in Applescript?

Viewed 81

I'm currently trying to make a new "class" in Applescript. I know that, without making an application, it is technically impossible.

But I tried to mimic it with an embedded script:

script specialText
    property value : ""
    on flip()
        return reverse of (characters of my value) as string
    end flip
end script

set x to specialText

set value of x to "Hello World"

x's flip()

This works great and returns "dlroW olleH" as expected, however:

script specialText
    property value : ""
    on flip()
        return reverse of (characters of my value) as string
    end flip
end script

set x to specialText

set value of x to "Hello World"

x's flip() = specialText's flip()

This returns true.

So my question now is, can I do something like this without making the new variable a reference to the original?

2 Answers

Close. AS doesn’t have classes, but you can create new instances of a script object just by executing the script block statement.

Wrap it in a handler like this:

to makeSpecialText()
    script specialText
        property value : ""
        on flip()
            return reverse of (characters of my value) as string
        end flip
    end script
    return specialText
end makeSpecialText

Create new instances by calling the handler, e.g.:

set x to makeSpecialText()
set y to makeSpecialText()
set z to makeSpecialText()

You now have three independent instances of the script object bound to x, y, and z, each with its own state.

Apress’ Learn AppleScript, 3rd edition (which I lead-authored) has a chapter on script objects covering libraries (semi-obsolete now as AS finally got native library support in macOS 10.10) and object-oriented programming (reasonably thorough given the length limitations of a 1000-page book).

Warning: This solution is very memory intensive and is not recommended for doing this! Foo's answer (the accepted one) will most likely fit your needs better.


Another way to do it would be to use the copy statement:

script specialText
    property value : ""
    on flip()
        return reverse of (characters of my value) as string
    end flip
end script

copy specialText to x

set value of x to "Hello World"

log x's flip() = specialText's flip()
log specialText's flip()
(*false*)
(**)

Note that the syntax of the copy command is not like the set-command. So it is not copy newVariable to oldVariable but rather copy oldVariable to newVariable.

Related