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?
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).