0

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) 
6
  • You don't want to get the "constructor", you want to get the A object, 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](); Commented Dec 21, 2017 at 9:35
  • Constructor for object is obj.__proto__.constructor Commented Dec 21, 2017 at 9:36
  • @AlexanderPoshtaruk it is not the same what about I asked. Commented Dec 21, 2017 at 9:37
  • Sorry. But then another approach: window.A = class A { constructor(name,age){ this.name = name this.age = age this.typeName = this.constructor.name } print(){ return ${this.name}, ${this.age} } }; var s = new A('rest', '1'); console.log(window[s.typeName]); Commented Dec 21, 2017 at 9:41
  • I need to use code in Node.js too. Commented Dec 21, 2017 at 9:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.