在这里,我正在实施具有所有国家/地区的GeoMap资产。在这种情况下,所有国家/地区都有其自己的类别,例如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()]();
至于字符串,capitalize
你可以参考这篇文章。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句