0

In php we can do this:

$classInstance = new MyClass();
$className = get_class_name($classInstance);
$newInstance = new $className; 

How can I do the same in javascript?

I tried with Object.creat and Object.assign, however when calling methods from the new class, the old was was still being referenced:

  const newInstance = Object.assign(
    Object.create(
      Object.getPrototypeOf(oldInstace)
    ),
    oldInstance
  );

  newInstance.method(); // "this" still referencing oldInstance
localhost
  • 845
  • 3
  • 14
  • 32
  • 1
    @CertainPerformance This is not a duplicate of that question. That question does not cover how to instantiate an object. It would be a useful question to link to in an answer though. – Omn Aug 18 '19 at 01:16
  • 1
    @Omn It looks like it to me. `new foo.constructor()` – CertainPerformance Aug 18 '19 at 01:17
  • 1
    @CertainPerformance that would be the correct answer, but I do not see that clearly explained anywhere. While the answer to this question may well be understood by carefully reading that page, none of those answers apply directly to this question. – Omn Aug 18 '19 at 01:28
  • It would be the correct answer with the proviso that you can't use it from the constructor as so: var foo = null; class Bar { ... constructor() { ..... foo = new this.constructor(); ..... } ... } > baz = new Bar(); Uncaught RangeError: Maximum call stack size exceeded Note that foo is definitely in scope here so had we done this from another method we should have correctly gotten another instance of the class. – Peter Gerdes Jun 29 '21 at 07:39

0 Answers0