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)
halfer
  • 19,824
  • 17
  • 99
  • 186
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

0 Answers0