Mixins

As we saw much earlier in this book, the inheritance pattern for JavaScript is different from the typical pattern seen in languages like C# and Java. JavaScript uses prototype inheritance that allows adding functions to a class quite easily and from multiple sources. Prototype inheritance allows for adding methods from multiple sources in a similar fashion to the much-maligned multiple-inheritance. The primary criticism of multiple inheritance is that it is difficult to understand which overload of a method will be called in a situation. This problem is somewhat alleviated in a prototype inheritance model. Thus we can feel comfortable using the approach of adding functionality from several sources, which is known as mixins.

A mixin is a chunk of code which can be added to existing classes to expand their functionality. They make the most sense in scenarios where the functions need to be shared between disparate classes where an inheritance relationship is too strong.

Let's imagine a scenario where this sort of functionality would be handy. In the land of Westeros, death is not always as permanent as in our world. However, those who return from the dead may not be exactly as they were when they were alive. While much of the functionality is shared between Person and ReanimatedPerson, they are not close enough to have an inheritance relationship. In this code you can see the extend function of underscore used to add mixins to our two people classes. It is possible to do this without underscore but, as mentioned earlier, there are some complex edge cases around extends which make using a library handy:

var _ = require("underscore");
export class Person{
}
export class ReanimatedPerson{
}
export class RideHorseMixin{
  public Ride(){
    console.log("I'm on a horse!");
  }
}

var person = new Person();
var reanimatedPerson = new ReanimatedPerson();
_.extend(person, new RideHorseMixin());
_.extend(reanimatedPerson, new RideHorseMixin());

person.Ride();
reanimatedPerson.Ride();

Mixins provide a mechanism to share functionality between diverse objects but do pollute the prototype structure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset