class instance from string

K

Kristoph

Greetings,

I have a String instance which contains the name of a class. Is there
some way I can instantiate that class from given the class name in the
string?

Many Thanks, in advance, for any assistance,

Kristoph
 
G

Geoff Stearns

I have a String instance which contains the name of a class. Is there
some way I can instantiate that class from given the class name in the
string?


If you are trying to do what I think you are, there's a few ways you
can do it.

Here's two examples:

// set up the class
function MyClass() {
this.foo = "bar";
}

// store the class name in a string
var classIdString = "MyClass";

// first method
var classInstance = new this[classIdString];

// second method
var classInstance2 = eval("new "+ classIdString);

// test them
alert(classInstance.foo);
alert(classInstance2.foo);
 
K

Kristoph

I have a String instance which contains the name of a class. Is there
some way I can instantiate that class from given the class name in the
string?

If you are trying to do what I think you are, there's a few ways you
can do it.

Here's two examples:

// set up the class
function MyClass() {
this.foo = "bar";

}

// store the class name in a string
var classIdString = "MyClass";

// first method
var classInstance = new this[classIdString];

// second method
var classInstance2 = eval("new "+ classIdString);

// test them
alert(classInstance.foo);
alert(classInstance2.foo);

var classInstance = this[classIdString];

.... that's exactly what I was looking for

Thank you very much.

]{
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,266
Latest member
DavidaAlla

Latest Threads

Top