mardi 11 avril 2017

Extending class from already defined ones. How to replace super()?

Given 2 defined classes M and N, I'd like to make M extend N.

For that I want to use setPrototypeOf() described in this answer (2nd solution).

Reflect.setPrototypeOf( M.prototype, N.prototype ) 

Also I want that class M constructor() to call class N constructor().

To achieve that I use the following call:

Reflect.construct( Reflect.getPrototypeOf( M.prototype ).constructor, args, M )

Note: I don't use N in construct() because I want it to work even when the class is not extended (or extended whith another a class).

It works in my test but I'm not sure it's the best way to do that.

class N {
  constructor() {
    console.log('N created')
  }
  get N() {
    return 'N-prop'
  }
}

class M {
  constructor(...args) {
    console.log('M created')
    return Reflect.construct(Reflect.getPrototypeOf(M.prototype).constructor, args, M)
  }
  get M() {
    return 'M-prop'
  }
}

Reflect.setPrototypeOf(M.prototype, N.prototype)

var m = new M
console.log(m.M, m.N)

Is there a better, proper way to do that?





Aucun commentaire:

Enregistrer un commentaire