0
class A {
  constructor() {
    this.test = 'test';
    this.b = null;    
  }
}

class B {
  constructor() {
  }

  log() {
    console.log("log: ");
    console.log(super.test);
  }
}

var a = new A()

const C = Object.assign(a, B);

console.log(C);
C.log();

Is it possible to extend instance of a class with class definition? ... in a way that method of B use A's property! I want to add a few methods to a few of A instances.

Tim Han
  • 168
  • 1
  • 12
RobM
  • 412
  • 4
  • 16

1 Answers1

0

You could create a third class C:

class A {
  a() {
    this.test = 1;
  }
}

class B extends A {
  b() {
    this.test = 2;
  }
}

class C extends B {}

var c = new C()
// c has a() and b() methods
c.a()
c.b()
console.log(c.test) // c.test === 2
Luca Steeb
  • 1,778
  • 3
  • 23
  • 44
  • I don't want to extend class. I have in your case a = new A(). – RobM Feb 14 '18 at 21:54
  • Well, why not? When I understood your question correctly, you want to use the methods from your B class for one specific A instance. What I do is instead of creating an instance of A is creating a new class C which has the methods from A & B, then you can create a new instance of class C instead. If you really want to add methods to an A class afterwards, then, well, I'd be interested in the use case... – Luca Steeb Feb 14 '18 at 22:02
  • I have to use instance not the definition of A. Use case: I got instances of message objects and a few of them (based on the condition) are also responses. I want to add two methods to this object. – RobM Feb 14 '18 at 22:10
  • Look at @AnandShanbhag answer here: https://stackoverflow.com/questions/29879267/es6-class-multiple-inheritance . This is almost what I want, but I want to use method in Organisation which uses property of Person. – RobM Feb 14 '18 at 22:18
  • I am currently not sure how to do this, but I can tell you that you need at least a separate function which does some crazy prototype stuff you don't really want to use.. Another method would be to assign a field of the a instance with a new C() instance and then use the methods like this: `var a = new A(); a.cInstance.yourAddedMethodFromC()` – Luca Steeb Feb 14 '18 at 22:50
  • I am aware of the second option. But I really want to have the same object as a = new A(), with all things done to this object but extended with a few methods. I don't want to change the rest of the code to use c.a.method() – RobM Feb 14 '18 at 22:55