javascript - JavaScript 中的动态实例化

标签 javascript object

我有一个下拉列表,其中包含可以实例化为 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/

相关文章:

ios - 从对象创建循环转换为在对象创建之间等待的 runBlock

javascript - JS 过滤两个对象数组。没有得到独一无二的

Angular4 - 检查嵌套对象项是否为空

javascript - 当属性为 0 或以下时从数组中删除对象 - Angular

php - 使用php动态创建表单元素

javascript - 为什么我的递归函数似乎只运行一次?

javascript - 将此(对象)传递到对象方法之一嵌套方法

javascript - Javascript 中的数组和对象复制

javascript - 为什么要在 Array.prototype.forEach() 中检查 null?

javascript - 滚动滚动条时保持广告在顶部可见