How to get the class prototype on the base of its name?
This is my attempt:
// Environment detection (Browser or Node.js) const isBrowser = new Function('try { return this === window } catch(e){ return false}') // or const isNode = new Function('try { return this === global }catch(e){ return false }') // Get the window or global object const getRoot = function(){ if (isBrowser()){ return (new Function('return window'))() } else{ return (new Function('return global'))() } } // This is my class class A { constructor(name,age){ this.name = name this.age = age this.typeName = this.constructor.name } print(){ return `${this.name}, ${this.age}` } } // Some JSON object (for example it is an DTO-object // that I got from server or client). Each object has // typeName property. const obj = {name: 'Bob', age: 30, typeName: 'A'} // I need to cast JSON-object to necessary type. // I expected to get the class prototype on the base of its name const root = getRoot() // window or global // get class A const _class = root[obj.typeName] // Oops... It is undefined Object.setPrototypeOf(obj,_class.prototype) console.log(obj.print()) UPD
I solved the problem:
const _proto = eval(`${obj.typeName}.prototype`); Object.setPrototypeOf(obj,_proto)
Aobject, which essentially means you want to use variable variables. See the duplicate. The sanest way is to use a mapping:let map = {A: A}; new map[obj.typeName]();${this.name}, ${this.age}} }; var s = new A('rest', '1'); console.log(window[s.typeName]);