Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the new operator with a variable

I'd like to do something like this:

var foo = function(){
   this.value = 1;
}
var bar = "foo";
var baz = new bar();
alert(baz.value)     // 1

Essentially, I want to create a new object from the string version of its name. Any ideas?

like image 959
Chiraag Mundhe Avatar asked Mar 22 '26 20:03

Chiraag Mundhe


1 Answers

var foo = function(){
   this.value = 1;
};
var bar = "foo";
var baz = new this[bar](); // "this" here refers to the global object (you could also use "window", but "this" is shorter)
alert(baz.value)     // 1

See also http://blog.brett-zamir.me/?p=24

like image 181
Brett Zamir Avatar answered Mar 24 '26 10:03

Brett Zamir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!