如何根据名称获取类原型?
这是我的尝试:
// 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
我解决了这个问题:
const _proto = eval(`${obj.typeName}.prototype`);
Object.setPrototypeOf(obj,_proto)