开发者

instance name as variable

开发者 https://www.devze.com 2023-02-12 02:28 出处:网络
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, s开发者_开发技巧o rather

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, s开发者_开发技巧o 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 ?


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;


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.


If it's a global you can use:

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

精彩评论

暂无评论...
验证码 换一张
取 消