crankshaft
crankshaft

Reputation: 2677

instance name as variable

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 ?

Upvotes: 2

Views: 919

Answers (3)

Chris Hogan
Chris Hogan

Reputation: 868

If it's a global you can use:

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

Upvotes: 0

David Tang
David Tang

Reputation: 93694

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;

Upvotes: 2

deceze
deceze

Reputation: 522500

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.

Upvotes: 2

Related Questions