Noah Freitas
Noah Freitas

Reputation: 17430

Using A String Value As the Name of a Function to Be Called

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

Answers (3)

Aprillion
Aprillion

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

jsfiddle

Upvotes: 0

Alex K.
Alex K.

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

Joseph Silber
Joseph Silber

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

Related Questions