Chiraag Mundhe
Chiraag Mundhe

Reputation: 384

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?

Upvotes: 3

Views: 232

Answers (1)

Brett Zamir
Brett Zamir

Reputation: 14345

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

Upvotes: 1

Related Questions