开发者

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜