Delegation

In the inheritance section we looked at one way to extend a class functionality, there is second way using delegation to extend functionality. With delegation, one object will contain a reference to a different object that it will hand off a request to perform the functionality.

The code below shows how to use delegation with the Bird class and Penguin class. The Penguin class has a reference to the Bird class and it delegates the call made to it's walk method over to Bird's walk method.

  1. // ES6
  2. class Bird {
  3. constructor(weight, height) {
  4. this.weight = weight;
  5. this.height = height;
  6. }
  7. walk() {
  8. console.log('walk!');
  9. }
  10. }
  11. class Penguin {
  12. constructor(bird) {
  13. this.bird = bird;
  14. }
  15. walk() {
  16. this.bird.walk();
  17. }
  18. swim() {
  19. console.log('swim!');
  20. }
  21. }
  22. const bird = new Bird(...);
  23. const penguin = new Penguin(bird);
  24. penguin.walk(); //walk!
  25. penguin.swim(); //swim!

A good discussion on 'behaviour delegation' can be found here.

原文: https://angular-2-training-book.rangle.io/handout/features/delegation.html