I want to be able to do something like this:
var MyObject = function(prop) {
this.property = prop;
};
var stringVar = 'MyObject';
var myObject = new stringVar(1); // This doesn't work.
assertTrue(myObject.property === 1);
I know that this will work:
var myObject = new window[stringVar](1);
but I was wondering if there was a more context neutral way of accomplishing it.
As a side note: I am obviously trying to avoid using eval().
This is a known limitation in Javascript. There’s no way to reference functions by string in a context-neutral way. What you have is all you can do.
So, if you were to have all this within a closure, it wouldn’t work. Your only option would be to have your constructor as a method of another object: