Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

oop

Here's what I'm trying to do -- this is pseudo code and doesn't work. Does anyone know how to accomplish this for real:

// Define the class MyClass = Class.extend({});  // Store the class name in a string var classNameString = 'MyClass';  // Instantiate the object using the class name string var myObject = new classNameString(); 
like image 793
Kirk Ouimet Avatar asked Sep 02 '09 06:09

Kirk Ouimet


2 Answers

Would it work if you did something like this:

var myObject = window[classNameString]; 

..?

like image 122
peirix Avatar answered Sep 20 '22 05:09

peirix


Here's a more robust solution that will work with namespaced functions:

var stringToFunction = function(str) {   var arr = str.split(".");    var fn = (window || this);   for (var i = 0, len = arr.length; i < len; i++) {     fn = fn[arr[i]];   }    if (typeof fn !== "function") {     throw new Error("function not found");   }    return  fn; }; 

Example:

my = {}; my.namespaced = {}; (my.namespaced.MyClass = function() {   console.log("constructed"); }).prototype = {   do: function() {     console.log("doing");   } };  var MyClass = stringToFunction("my.namespaced.MyClass"); var instance = new MyClass(); instance.do(); 
like image 38
Yuriy Nemtsov Avatar answered Sep 20 '22 05:09

Yuriy Nemtsov