vendredi 1 juillet 2016

how do you implement classes with property subsets?

I have 3 classes ...

class1 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.toClass2 = function() {
      // TODO: return this as an instance of class2;
      // the conversion would remove the unwanted 'b' property
    }
    this.toClass3 = function() {
      // TODO: return this as an instance of class3;
      // the conversion would remove the unwanted 'a' property
    }
  }
}

class2 {
  constructor(a, c) {
    this.a = a;
    this.c = c;
  }
}

class3 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
}

The following statements are true ...

  • class1 could extend class2
  • class1 could extend class3
  • class1 could NOT extend class2 AND class3 (multiple inheritance not supported in JavaScript and multiple inheritance would give the derived class 4 properties, but I only want 3)

  • class2 has a subset of class1's properties

  • class3 has a subset of class1's properties

QUESTION: How can I best implement the classes in JavaScript or TypeScript so that the toClass2 and toClass3 conversion methods work? Are there any design patterns for this? Thank you

Aucun commentaire:

Enregistrer un commentaire