Load multiple instances of a script?

I have been experimenting with creating more object oriented scripts (because I have a lot of them and plan to have more). I have a string “class”, a file “class”, etc, each with its own set of “properties” (global variables) and “methods” (subroutines). I have read that I can create multiple “instances” by loading the script multiple times, assigning it to a different variable each time:


global strObjectA
set strObjectA to load script file filePath
global strObjectB
set strObjectB to load script file filePath

I’ve also read that this is a bad idea, although the person who said so didn’t say why. Is it a bad idea (especially given the growing number of subroutines in my string class)? Also, is it okay to load a script within itself? For example, would it be bad to do this within my string class?


global Str_source
set Str_source to {"a ", "list of ", "  Items to trim"}
on trim(theseCharacters)
	if class of Str_source is list then
		repeat with i from 1 to (count of Str_source)
                       set thisStr to load script file pathToThisFileWeAreInRightNow 
			set item i of Str_source to thisStr's trim_in_string(theseCharacters)
		end repeat
	end if
end trim

Hi,

both methods are no problem. Rather this a part of the power of AppleScript.
It can call handlers recursively and is able to handle inheritance and polymorphism.

But consider that a script is single threaded

Not good. Use ‘load script’ for importing library scripts only.

To create new script object instances within a script, define a constructor handler like this:

on makeFoo(x)
	script Foo
		property y : 2
		
		on doSomething(z)
			return x + y * z
		end doSomething
	end script
end makeFoo

-- TEST
set foo1 to makeFoo(1)
set foo2 to makeFoo(3)

foo1's doSomething(3) --> 7
foo2's doSomething(5) --> 13