moock.org is supported in part by


July 09, 2003

reader mail: dynamic variable names

stefan asks:
*********************
I wanna use a kind of dynamic variable on the left side of "=".

Something like:
var iname = "myobjectinstancename";
var eval(iname) = new myClass();

To say it frankly I do not exspect to get this working.

Or a compiler (AS -> SWF) on the server-side would solve this problem.

Do you have any idea?


colin answers:
*********************
if your code is on a frame in a timeline, you can use the [] operator to create the variable name from a string. as in:

function MyClass () {
}
MyClass.prototype.hello = function () {
trace("hello world");
}

var iname = "myobjectinstancename";
this["iname"] = new myClass();

iname.hello(); // Displays "hello world"

as for a server-side compiler, you could investigate Ming:
http://ming.sourceforge.net/

Posted by moock at July 9, 2003 11:15 AM
Comments

You can also use the 'set' command:

//-- use the set command
function MyClass () {}
myClass.prototype.hello = function() {
trace( "hello world" );
}

for ( i=0; i<=3; i++ ) {
set( "myobjectinstancename" + i, new myClass() );
}

myobjectinstancename1.hello(); // Displays "hello world"
myobjectinstancename2.hello(); // Displays "hello world"
myobjectinstancename3.hello(); // Displays "hello world"

Posted by: Scott Janousek at July 18, 2003 01:10 AM

I think what Stefan is asking for is more like this:

var iname = "myobjectinstancename";
this[iname] = new myClass();

myobjectinstancename.hello(); // Displays "hello world"

This also works. Right?

Posted by: D Schafer at July 10, 2003 01:07 PM

you can also concatenate strings or get objects properties

obj_01 = new Object();
obj_01.value = 100;
//
objnum = 01;
trace(this["obj_"+objnum].value); // Displays 100

Posted by: sangles at July 9, 2003 04:08 PM