1

Possible Duplicate:
create object from dynamic classname - ReflectionClass in JS?

Is it possible to do this in javascript?

var objectName = "object";
var object = new objectName();

or something along these lines?

2
  • As am not i am pointed out, yes, to an extent. Why exactly do you need this, though? Commented Jan 31, 2012 at 15:20
  • Better use Factory to create objects. Commented Jan 31, 2012 at 15:25

3 Answers 3

7

If the constructor is defined globally...

var object = new window[objectName]();

If not, you'd need to use eval or the Function constructor. Before you did that, I'd try to find a different way to do what you're doing.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 the OP would need correct casing in his example also; var objectName = "Object";
@AlexK.: You're right, assuming the native Object constructor is desired.
1

You can archieve that using eval(). Eval basically interprets a string like it were a script line. Althought, some developers consider it's a dangerous function to your daily use, other's don't. Read more here.

Example of your code using eval (corrected):

var objectName = "Object";
var object = new (eval(objectName));
eval("object.name = \"Nice!\""); // you don't need this, just an example of eval capabilities

document.write(object.name);

Running: http://jsfiddle.net/RxNsd/4/

5 Comments

Don't downvote this answer. It's the only solution for local constructors.
@RobW agree, if there is no reasonable alternatives to using eval to achieve something then eval or eval-likes are fine =)
People freak out when they see eval. I don't know why. A person could also use the Function constructor, but its still effectively evaling the string. Function('return new ' + objectName + '()')()
@RobW: You need to wrap the eval call in (). new (eval(objectName)); Otherwise the eval function itself becomes the single operand of new.
@amnotiam That's correct. The right usafe is var objectName = "Object";var object = new (eval(objectName));.
0

No, it's not possible the way you coded. But with a little change...

var object = { objectName: "object" };
alert(object.objectName); // Pops up "object"

If you prefer the new syntax, there must exist a constructor function.

function ObjectName(name) // This is the "constructor" function
{
    this.objectName = name;
}

var object = new ObjectName("object");
alert(object.objectName); // Pops up "object"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.