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.
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”.
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.
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"]();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With