我有一个下拉列表,其中包含可以实例化为 JavaScript“类”的货币分类。我目前使用 switch 语句来完成此操作,但我绝对确定有更 Eloquent 方法可以做到这一点。那么,有人可以告诉我更好的方法吗?
是否有更好的动态实例化类的方法?
function ddlCurrency_selectedIndexChanged() {
var currency = null;
switch (this.value) {
case "Dollar":
currency = new Dollar(null);
break;
case "Reais":
currency = new Reais(null);
break;
}
// Do something with the class here
};
这是类:
以防万一你想见他们。
// ------------------------
// CLASS - Base Class
function Currency(country, code, imageURL, name) {
this.country = country; //EXAMPLE: America
this.code = code; //EXAMPLE: USD
this.imageURL = imageURL; //EXAMPLE: "http://someplace/mySymbol.gif"
this.name = name; //EXAMPLE: Dollar
this.amount = parseFloat("0.00"); //EXAMPLE: 100
};
// CLASS
function Pound(imageURL) {
Currency.call(this, "Greate Britain", "GBP", imageURL, "Pound");
};
Pound.prototype = new Currency();
Pound.prototype.constructor = Pound;
// CLASS
function Dollar(imageURL) {
Currency.call(this, "America", "USD", imageURL, "Dollar");
};
Dollar.prototype = new Currency();
Dollar.prototype.constructor = Dollar;
// CLASS
function Reais(imageURL) {
Currency.call(this, "Brazil", "BRL", imageURL, "Reais");
};
Reais.prototype = new Currency();
Reais.prototype.constructor = Reais;
更新:
使用 eval()
也可以。奇怪的是,我看到人们对使用它投了反对票……尽管我不知道为什么。就我个人而言,我更喜欢它,因为您可能不会对 window
对象产生任何影响。一个很好的例子就是某些 AMD 风格的异步加载对象......它们不会挂断 window
。
使用 eval 的示例:
var currency = eval('new Dollar()');
最佳答案
假设您的顶级对象是窗口(如果您在浏览器中):
currency = new window[this.value](null);
这是可行的,因为您所有的类都只是全局对象的属性,window[property]
检索一个属性。
关于javascript - JavaScript 中的动态实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6914108/