0

I have a use case where I need to persist the name of a given class in a cookie so that I can create an instance of it later when the client returns. I would like to be able to do something like this:

class MyClass {
}

var a1 = new MyClass()
var className = a.class.name()//like in Java..
var a2 = Class.forName(className).newInstance();

Is this possible in ES6? Specifically I am looking for some way to get the name fo the class as a string,

Runar Halse
  • 3,528
  • 10
  • 39
  • 59
  • I don't think this question should be down vote. It's not bad question or seem duplicated exactly. Upvoted. – Elec Jul 30 '23 at 08:46

1 Answers1

1

You should be able to get the name of the class by calling a1.constructor.name1

Since classes are really fancy syntax for functions, if the class exists on the window object you could probably then do something like var a2 = new window[className](); but that really depends what scope you are working in.

Community
  • 1
  • 1
Ted A.
  • 2,264
  • 17
  • 22