2

I have searched this site and also googled but can't seem to find the answer.

I need to create object instances dynamically where the instance name is provided as variable, so rather than access the object properties using:

var n = 'abcd';

eval('var '+n+' = new myinst();');

abcd.property = value;

I need to access using a variable:

['abcd'].property = value;

But this does not appear to work - what am I missing ?

3 Answers 3

2

You shouldn't be using eval in that way. You can easily assign "dynamic" variables to some base object instead:

var baseObj = {};
var n = 'abcd';

baseObj[n] = new myinst();
baseObj[n].property = value;

This gives you full control over the variable, including the ability to delete it,

delete baseObj[n];

Or check if it exists,

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

1 Comment

Thanks so much, it's easy when you know how :-)
2

You can do "variable variables" using the array notation, but you need to provide a context for it. In the global scope, that would be the window:

var foo = 'bar';
window[foo] = new myinst();
window[foo].property = 'baz';
alert(bar.property);

Substitute window for whatever other scope a variable variable should live in. Variable variables are really an anti-pattern that shouldn't be used though.

Comments

0

If it's a global you can use:

var n = 'abcd';
window[ n ] = new myInst();
window[ n ].property = value;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.