panych
10/23/2016 - 12:57 PM

Copy method to class in ES2015

Copy method to class in ES2015

class A {
  constructor(msg) {
    this.message = msg ? msg : 'default A message'
  }
  sayHello(additional) {
    console.log(`${this.message}${additional ? ` and ${additional}` : ''}`)
  }
}

class B {
  constructor() {
    this.message = 'default B message'
  }

  sayHello() {
    A.prototype.sayHello.apply(this, arguments)
  }
}

/*
Usage:
var a = new A;
var b = new B;
a.sayHello(); // default A message
b.sayHello(); // default B message
a.sayHello('more!'); // default A message and more!
b.sayHello('more more more!'); // default B message and more more more!
*/