Prisoner ZERO
Prisoner ZERO

Reputation: 14166

Dynamic Instantiation In JavaScript

I have a drop-down list containing classifications of currencies which can be instantiated as a JavaScript "class". I currently use a switch statement to accomplish this, but I'm absolutely sure there's a more eloquent way to do so. So, can anyone out there show me a better way?

Is There a Better Way To Dynamically Instantiate a Class?:

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
};

Here Are The Classes:
Just in case you wanted to see them.

// ------------------------
// 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;

UPDATE:
Using eval() also works. Oddly enough, I've seen people voted downward for using it...although, I don't know why. Personally, I'm inclined to like it better because you may not have anything coming-off of the window object. A good example of that is in the case of certain AMD-style asynchronously loaded objects...they do not hang-off window.

EXAMPLE using eval:

var currency = eval('new Dollar()');

Upvotes: 3

Views: 1274

Answers (1)

david
david

Reputation: 471

Assuming your top level object is window (in case you are in a browser):

currency = new window[this.value](null);

This works since all your classes are just properties of the global object and window[property] retrieves a property.

Upvotes: 4

Related Questions