Search code examples
javascriptcoffeescript

Call "new" programmatically in Coffeescript


Possible Duplicate:
How do I make JavaScript Object using a variable String to define the class name?

I want to be able to call the new on things programmatically. So for example, if I have these two classes:

class Bird
   constructor: (@name) ->

class Snake
   constructor: (@name) ->

I can call s = new Snake("Sam"). Now, what I want to do is

bird_class = "Bird"
b = new bird_class()

and be able to construct a bird object from a string. Is this possible in CoffeeScript or Javascript?


Solution

  • If you kept your classes in an object you could always:

    var animals = {
      Snake: Snake,
      Bird: Bird
    };
    
    new animals["Snake"]();
    

    As per your comment, some pattern like this would let you register classes on the fly. It's raw, but might give you an idea:

    var zoo = {
      animals: {},
    
      add: function (animal) {
        this.animals[animal.name] = animal;
      },
    
      make: function(name) {
        if (this.animals[name]) {
          return new this.animals[name]();
        }
      }
    };
    
    function Snake() {};
    zoo.add(Snake);
    var snake = zoo.make('Snake');