super pantera
super pantera

Reputation: 165

javascript type error "is not a constructor"

I have several classes for representing different types of tables. I put names of classes to the dictionary. I take class name from the dictionary by key and try to create instance of class by using construction "new var_with_class_name()" but get an error "TypeError: dictionary[model_name] is not a constructor". This code is packed as require.js module. Code:

define("models", ["jquery", "ui"], function($, ui){

var TimeTableRow = function()
{ /* class methods definitions */ }
var WayTableRow = function()
{ /* ... */ }
var ModelsDictionary = function()
{
   var self = this;
   self.getModel = function(model_name)
   {
      var dictionary = {'time':"TimeTableRow", 'way':"WayTableRow"};
      return new dictionary[model_name]();
   }
}
return new ModelsDictionary();
});

Example of usage from another require.js module (I skip all requirejs configs and imports, just line of code that throws described error): var tableRow = models.getModel(item_type);

Upvotes: 1

Views: 8478

Answers (1)

user2246674
user2246674

Reputation: 7719

Given

 var dictionary = {'time':"TimeTableRow", 'way':"WayTableRow"};
 return new dictionary[model_name]();

dictionary[model_name] evaluates to a string (or undefined) and new ("x")() is nonsense. Instead, the lookup should evaluate to the actual constructor functions:

 var dictionary = {'time': TimeTableRow, 'way': WayTableRow};
 return new dictionary[model_name]();

Remember that functions are just objects in JavaScript.

Upvotes: 1

Related Questions