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?
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
精彩评论