Reputation: 17430
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()
.
Upvotes: 0
Views: 65
Reputation: 22340
not sure if this is what you want:
var obj = {"myObject": function(prop) {this.property = prop; return this;},
"MySecondObject": "probably second function"
},
str = "myObject";
var myChildObj = obj[str]("test");
alert(myChildObj.property);
Upvotes: 0
Reputation: 175906
Use a namespace so you always know the hierarchy, e.g. the following will work on a desktop .js file run with the windows scripting host (where there is no window
)
var MyNameSpace = {};
MyNameSpace.MyObject = function(prop) {
this.property = prop;
};
var stringVar = 'MyObject';
var myObject = new MyNameSpace[stringVar](123);
Upvotes: 2
Reputation: 220066
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:
var constructors = {
MyObject: function(prop) {
this.property = prop;
}
}
var stringVar = 'MyObject';
var myObject = new constructors[stringVar](1);
Upvotes: 3