0

Is there a way to instantiate a new object from a class based on a variable in ES6?

This is my scenario:

class SomeClass {
    hasMany(what){

        var instance = new window[what]();

        var owned_objects = instance.allOwnedBy(this.constructor.name, self.id);

        return instance;
    }
}

However, this returns Uncaught TypeError: window.Group is not a constructor(…)

the hasMany is located within a Class. So what I want to achieve is that the function within this class, should instantiate another class based on the name of that class passed as a variable, and then return the instance.

Ole Haugset
  • 3,709
  • 3
  • 23
  • 44

1 Answers1

0

How are you defining class Group?

In my tests, it'd work if you specifically set the class as a property of window. So:

window.Group = class {...}

Then you can do:

var instance = new window['Group']();
ezakto
  • 3,174
  • 22
  • 27
  • It would work, yes, but you still shouldn't do that. – Bergi Sep 29 '16 at 21:36
  • 1
    I'm not really a "don't pollute the window object" activist, but yeah. He could also make a dict with all the references and access that. – ezakto Sep 29 '16 at 21:40