将new运算符与变量一起使用

时间:2011-07-04 06:15:13

标签: javascript new-operator

我想做这样的事情:

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

基本上,我想从其名称的字符串版本创建一个新对象。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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

另见http://blog.brett-zamir.me/?p=24