Often times when I am making dynamic scripts in Flash or JavaScript, I want to call an object method using a string. It may be a situation where I am stuck using fscommand (due to a customer request of a Flash version <8) or just writing script with script.
The problem that comes with this method is the advent of ActionScript 3 with Flash CS3/Flex 2 and the rising use in namespaces by JavaScript developers (myself included). Both encour a heavy usage of object methods instead of one-off functions. Dynamically calling singleton functions is easy, you can just use subscript notation, e.g. object[‘member/method’]. What you can’t do with this method is pass it any dot syntax and expect it to work e.g. object[‘subobject.method’]. The subscript notation is only meant to work one level. So the previous example won’t work. In order to fix this issue and to make sending object methods/members in a single string a little easier, I wrote a function that takes a string and a base object (the default is the window object if no object reference is passed) and returns the method/member. (I know at this point that some will simply direct me to ECMAScript’s built in eval() function, but I personally avoid using it at all costs as it can have unintended, and unsecure results. I’ll let Stephen Chapmen tell you because this article is about something else.)