Dynamically Referencing Variables and Methods in ActionScript

18 May 2010
Posted by xeophin

Sometimes, the state of an object decides which method has to be executed. Instead of an unwieldy switch construction like this ...

switch (task) {
 
    case "sleep":
    sleep();
    break;
 
    case "walk":
    walk();
    break;
}

... you can use the someObject[someExpression] notation. This works for any object, and you can use it to access both variables and methods. All those lines from above become this:

this[task]();

Much faster. Only problem I have yet to figure out: what happens, when there is no method by this name?

Sometimes, the state of an object decides which method has to be executed. Instead of an unwieldy `switch` construction like this ...switch (task) { case "sleep": sleep(); break; case "walk": walk(); break;}... you can use the `someObject[someExpression]` notation. This works for any object, and you can use it to access both variables and methods. All those lines from above become this:this[task]();Much faster. Only problem I have yet to figure out: what happens, when there is no method by this name?

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
By submitting this form, you accept the Mollom privacy policy.


Navigation



Languages