tags:

views:

775

answers:

4

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

// 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();
+3  A: 

Would it work if you did something like this:

var myObject = window['classNameString']();

..?

peirix
That worked. peirix you are awesome. You think it's cross-browser compatible?
Kirk
Think you meant `window[classNameString]` (no quotes). Breaks as soon as `MyClass` is moved to a lower (i.e. `function`) scope. @kirk: yes this is cross-browser.
Crescent Fresh
+1  A: 

If MyClass is global, you can access it as a property of window object (assuming your code runs in a browser) using subscript notation.

var myObject = new window["MyClass"]();
Chetan Sastry
+1  A: 

BTW: window is the reference to the global Object in browser JavaScript. Which is also this, and should work even in non-browser environments if you are in the global scope.

var obj = new this[classNameString]();

However, there really is no reason to use a string. JavaScript functions are themselves objects, just like strings which are objects also.

bucabay
+1  A: 

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();
GeorgeCalm