0

Quick question regarding variable scope in ActionScript 2.0. Did some testing today and was wondering how you would target a function's local variable through a concatenated variable string.

For example:

var txt = "Hello World"; 

function testing(msg) {
    var test1 = msg; 
    trace(this["test"+1]); 
}

testing(txt); 

I'd expect the trace to be "Hello World" but rather is given "undefined". So if variables created outside functions are created on the main timeline, where are local function variables created and how would you access them?

2 Answers 2

1

Variables you declare inside a function are not added to the this object. You would reference them just by the variable name:

function testing(msg) {
  var test1 = msg; 
  trace(test1); 
}

There isn't any other way that I know of (other than eval, and you generally want to avoid that) to reference the name of a local variable using a string containing its name.

If you need to somehow reference it by name then you would have to put it inside some other container. Either define a local object and make these variables members of it, or make this function a method on a class and use class variables.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply Herms. Thanks for clarifying that local function variables aren't added to the "this" object. I had originally assumed most variables declared would be added to the timeline where they were declared. I'll have to test out storing them into an object.
1

As far as I can remember, you can't. If you have test1, test2, test3, ... and so on, why not make it an array called test? Then you're test[0], test[1], test[2], ....

If you must use test1 though, then one way is to put it into an object.

var obj = {};
obj.test1 = msg;

trace(obj["test" + 1]);

1 Comment

Thanks for the reply and example Manish. Reinforcing that I should use objects to store those variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.