|
|||||||
Create object from string
Время создания: 13.07.2018 15:30
Текстовые метки: javascript create object string class
Раздел: Javascript
Запись: Velonski/mytetra-database/master/base/1529565639tvgibrrpc4/text.html на raw.githubusercontent.com
|
|||||||
|
|||||||
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. javascript shareimprove this question edited Sep 25 '15 at 3:02 Unheilig 11.5k165083 asked Mar 21 '12 at 11:42 chchrist 5,736113574 what do you hope to do with it? – Joseph Mar 21 '12 at 11:44 1 What's the rule to convert product to var p = new Product? I can understand new Product, but why p? – Felix Kling Mar 21 '12 at 11:44 @chchrist: That sounds dangerous, especially if the string comes from the user... why do you think that is this a good idea? Have you considered any alternative approaches? – Mark Byers Mar 21 '12 at 11:44 possible duplicate of Instantiate a JavaScript Object Using a String to Define the Class Name – Scott Dudley Sep 23 '15 at 19:44 add a comment 3 Answers active oldest votes up vote 61 down vote accepted 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"](); shareimprove this answer answered Mar 21 '12 at 11:54 ZER0 15.8k33443 3 That's a much nicer solution than mine +1 – Matt Fellows Mar 21 '12 at 11:57 I've tried to create an object using new window["Namespace.MyClass"](), but looks like it's not working. How can we create objects when class contains in modules? – Narendra V Jan 9 '14 at 15:50 @NarendraV try new window["Namespace"]["MyClass"]() ? (This is just a guess, I don't know that this will work) – Matt Fellows Jan 10 '14 at 11:53 @NarendraV, you can use the square bracket notation instead of dot notation, not both: you basically tried to get a property named "Namespace.MyClass" from window where what you were looking was get Namespace from window, and then from Namespace, MyClass. @MattFellows shown the proper way to do so. You can also create a function like: function getReference(string, root) { root = root || this; return string.split(".").reduce(function(ref, item) { return ref[item] }, root) };, and use as var o = new getReference("Namespace.MyClass")(). it's a very simple one, you can make it better. – ZER0 Jan 12 '14 at 10:47 add a comment up vote 6 down vote Well you could always use the hideously insecure and illadvised eval(). e.g. var myStr = "Product" var p = eval("new " + myStr + "()"); or that might be: var myStr = "Product" eval("var p = new " + myStr + "()"); But it's fraught with potential vulnerabilities, especially if the string is coming from user input. shareimprove this answer answered Mar 21 '12 at 11:47 Matt Fellows 5,43142454 try searching for "use strict" for eval – Joseph Mar 21 '12 at 11:50 2 This could be much better solved with a name -> constructor function map. – Felix Kling Mar 21 '12 at 11:54 +1 When the input generated by a program, perfect – smirkingman May 2 '13 at 19:41 @FelixKling I wish there was an example of the name->constructor function map – slashdottir May 31 '17 at 17:41 1 @slashdottir: var constructorMap = {Product: Product}; var p = new constructorMap[myStr](); – Felix Kling May 31 '17 at 17:43 show 1 more comment up vote 1 down vote Just another implementation: var nameOfThang = 'Person'; var nameOfThingzName = 'The Dude'; var thangs = { Person: {name: 'Legowski'}, Cars: {} }; var person = new (eval(thangs[nameOfThang].constructor))(); person.name = new (eval(thangs.Person.name.constructor))(nameOfThingzName) .toString(); console.log('@thang, #Person', person); shareimprove this answer answered Jan 9 '14 at 23:12 Cody 6,67124232 |
|||||||
Так же в этом разделе:
|
|||||||
|
|||||||
|