Guid
Guid

Reputation: 2216

clone an object from the ancestor

In Javascript (ES6), I defined a tree of inherited classes :

class A {
  constructor () {
    (...)
  }
}

class B extends A {
  constructor () {
    (...)
    super();
  }
}

class C extends B {
  constructor () {
    (...)
    super();
  }
}

And so on (a class D extends B too, etc).

Now, in A, I want to write a function resolve that clone the current object and change only some of its fields.

class A {
  (...)
  resolve() {
    // I want to clone this
    const newClass = ???
  }
}

Is it possible to get the nested inherited constructor from A?
For instance, if I'm a C, is it possible to create a new C from resolve?

Otherwise, is it possible to clone this with all the functions are properties defined in the inherited classes?

Upvotes: 2

Views: 42

Answers (1)

Nebula
Nebula

Reputation: 7151

Try using this.constructor:

class A {
  foo() { return new (this.constructor) }
}

class B extends A {
  jj() { console.log('jj') }
}

(new B).foo().jj()

Upvotes: 2

Related Questions