gpt4 book ai didi

javascript - 对变量使用 new 运算符

转载 作者:行者123 更新时间:2023-11-29 15:50:07 24 4
gpt4 key购买 nike

我想做这样的事情:

var foo = function(){
this.value = 1;
}
var bar = "foo";
var baz = new bar();
alert(baz.value) // 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

关于javascript - 对变量使用 new 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6567921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com