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();
Would it work if you did something like this:
var myObject = window[classNameString];
..?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With