Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object from string

Tags:

Is it possible to create a new object using a string? For example, how can I convert the string "product" to var p = new Product?

Thanks in advance.

EDIT

What I want to do is to have a menu with <a href="#home"></a><a href="#products">products</a> and create the corresponding object from the href each time.

like image 913
chchrist Avatar asked Mar 21 '12 11:03

chchrist


People also ask

Can I create object with String?

There are two ways to create a String object: By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”.

How do I create a object in typescript?

Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.


1 Answers

If you know the context, yes. Let's say you're in a browser environment and Person is a global constructor. Because any global variable is a property of the global object, it means you can access to Person through the global object window:

var p = new Person() 

Is equivalent to:

var p = new window.Person() 

So you can use the square bracket notation:

var p = new window["Person"](); 

Of course this is valid for every kind of object. If you don't want pollute the global scope, you can have:

var mynamespace = {};  mynamespace.Person = function Person() {..}  var p = new mynamespace["Person"](); 
like image 53
ZER0 Avatar answered Sep 20 '22 16:09

ZER0