gpt4 book ai didi

javascript - 我们可以在 javascript 中使用字符串获取类的对象吗?

转载 作者:行者123 更新时间:2023-11-30 12:38:51 28 4
gpt4 key购买 nike

在这里,我正在实现一个包含所有国家/地区的 GeoMap Assets 。在此,所有国家/地区都有自己的类别,例如 BTNMongolia、BTNHungary 等。我只有国家/地区名称才能获取对象,并且基于国家/地区名称,我想获得该国家/地区类别的对象。我正在这样做。

function countryObject(country) {
switch (country) {
case 'mongolia':
return new BTNMongolia();
case 'mongolia':
return new BTNHungary();
case 'mongolia':
return new BTNComoros();
case 'mongolia':
return new BTNAntiguaandBarbuda();
case 'mongolia':
return new BTNSouthKorea();
case 'mongolia':
return new BTNAustralia();
case 'mongolia':
return new BTNTajikistan();
default:
return null;
}
}

在这里,为了获取对象,我想从国家名称本身获取国家类别的对象。有没有捷径可以做到这一点?

最佳答案

主要思路如下,需要检查是否存在返回null:

return new window["BTN" + country.capitalize()]();

如果你的类在命名空间下,你可以这样做:

return new myspaces["BTN" + country.capitalize()]();

字符串大写可以引用这个post .

关于javascript - 我们可以在 javascript 中使用字符串获取类的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25202736/

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