Mixins

JavaScript’s object mechanism does not automatically perform copy behavior when you “inherit” or “instantiate”. Plainly, there are no “classes” in JavaScript to instantiate, only objects. And objects don’t get copied to other objects, they get linked together (more on that in Chapter 5).

Since observed class behaviors in other languages imply copies, let’s examine how JS developers fake the missing copy behavior of classes in JavaScript: mixins. We’ll look at two types of “mixin”: explicit and implicit.

Explicit Mixins

Let’s again revisit our Vehicle and Car example from before. Since JavaScript will not automatically copy behavior from Vehicle to Car, we can instead create a utility that manually copies. Such a utility is often called extend(..) by many libraries/frameworks, but we will call it mixin(..) here for illustrative purposes.

  1. // vastly simplified `mixin(..)` example:
  2. function mixin( sourceObj, targetObj ) {
  3. for (var key in sourceObj) {
  4. // only copy if not already present
  5. if (!(key in targetObj)) {
  6. targetObj[key] = sourceObj[key];
  7. }
  8. }
  9. return targetObj;
  10. }
  11. var Vehicle = {
  12. engines: 1,
  13. ignition: function() {
  14. console.log( "Turning on my engine." );
  15. },
  16. drive: function() {
  17. this.ignition();
  18. console.log( "Steering and moving forward!" );
  19. }
  20. };
  21. var Car = mixin( Vehicle, {
  22. wheels: 4,
  23. drive: function() {
  24. Vehicle.drive.call( this );
  25. console.log( "Rolling on all " + this.wheels + " wheels!" );
  26. }
  27. } );

Note: Subtly but importantly, we’re not dealing with classes anymore, because there are no classes in JavaScript. Vehicle and Car are just objects that we make copies from and to, respectively.

Car now has a copy of the properties and functions from Vehicle. Technically, functions are not actually duplicated, but rather references to the functions are copied. So, Car now has a property called ignition, which is a copied reference to the ignition() function, as well as a property called engines with the copied value of 1 from Vehicle.

Car already had a drive property (function), so that property reference was not overridden (see the if statement in mixin(..) above).

“Polymorphism” Revisited

Let’s examine this statement: Vehicle.drive.call( this ). This is what I call “explicit pseudo-polymorphism”. Recall in our previous pseudo-code this line was inherited:drive(), which we called “relative polymorphism”.

JavaScript does not have (prior to ES6; see Appendix A) a facility for relative polymorphism. So, because both Car and Vehicle had a function of the same name: drive(), to distinguish a call to one or the other, we must make an absolute (not relative) reference. We explicitly specify the Vehicle object by name, and call the drive() function on it.

But if we said Vehicle.drive(), the this binding for that function call would be the Vehicle object instead of the Car object (see Chapter 2), which is not what we want. So, instead we use .call( this ) (Chapter 2) to ensure that drive() is executed in the context of the Car object.

Note: If the function name identifier for Car.drive() hadn’t overlapped with (aka, “shadowed”; see Chapter 5) Vehicle.drive(), we wouldn’t have been exercising “method polymorphism”. So, a reference to Vehicle.drive() would have been copied over by the mixin(..) call, and we could have accessed directly with this.drive(). The chosen identifier overlap shadowing is why we have to use the more complex explicit pseudo-polymorphism approach.

In class-oriented languages, which have relative polymorphism, the linkage between Car and Vehicle is established once, at the top of the class definition, which makes for only one place to maintain such relationships.

But because of JavaScript’s peculiarities, explicit pseudo-polymorphism (because of shadowing!) creates brittle manual/explicit linkage in every single function where you need such a (pseudo-)polymorphic reference. This can significantly increase the maintenance cost. Moreover, while explicit pseudo-polymorphism can emulate the behavior of “multiple inheritance”, it only increases the complexity and brittleness.

The result of such approaches is usually more complex, harder-to-read, and harder-to-maintain code. Explicit pseudo-polymorphism should be avoided wherever possible, because the cost outweighs the benefit in most respects.

Mixing Copies

Recall the mixin(..) utility from above:

  1. // vastly simplified `mixin()` example:
  2. function mixin( sourceObj, targetObj ) {
  3. for (var key in sourceObj) {
  4. // only copy if not already present
  5. if (!(key in targetObj)) {
  6. targetObj[key] = sourceObj[key];
  7. }
  8. }
  9. return targetObj;
  10. }

Now, let’s examine how mixin(..) works. It iterates over the properties of sourceObj (Vehicle in our example) and if there’s no matching property of that name in targetObj (Car in our example), it makes a copy. Since we’re making the copy after the initial object exists, we are careful to not copy over a target property.

If we made the copies first, before specifying the Car specific contents, we could omit this check against targetObj, but that’s a little more clunky and less efficient, so it’s generally less preferred:

  1. // alternate mixin, less "safe" to overwrites
  2. function mixin( sourceObj, targetObj ) {
  3. for (var key in sourceObj) {
  4. targetObj[key] = sourceObj[key];
  5. }
  6. return targetObj;
  7. }
  8. var Vehicle = {
  9. // ...
  10. };
  11. // first, create an empty object with
  12. // Vehicle's stuff copied in
  13. var Car = mixin( Vehicle, { } );
  14. // now copy the intended contents into Car
  15. mixin( {
  16. wheels: 4,
  17. drive: function() {
  18. // ...
  19. }
  20. }, Car );

Either approach, we have explicitly copied the non-overlapping contents of Vehicle into Car. The name “mixin” comes from an alternate way of explaining the task: Car has Vehicles contents mixed-in, just like you mix in chocolate chips into your favorite cookie dough.

As a result of the copy operation, Car will operate somewhat separately from Vehicle. If you add a property onto Car, it will not affect Vehicle, and vice versa.

Note: A few minor details have been skimmed over here. There are still some subtle ways the two objects can “affect” each other even after copying, such as if they both share a reference to a common object (such as an array).

Since the two objects also share references to their common functions, that means that even manual copying of functions (aka, mixins) from one object to another doesn’t actually emulate the real duplication from class to instance that occurs in class-oriented languages.

JavaScript functions can’t really be duplicated (in a standard, reliable way), so what you end up with instead is a duplicated reference to the same shared function object (functions are objects; see Chapter 3). If you modified one of the shared function objects (like ignition()) by adding properties on top of it, for instance, both Vehicle and Car would be “affected” via the shared reference.

Explicit mixins are a fine mechanism in JavaScript. But they appear more powerful than they really are. Not much benefit is actually derived from copying a property from one object to another, as opposed to just defining the properties twice, once on each object. And that’s especially true given the function-object reference nuance we just mentioned.

If you explicitly mix-in two or more objects into your target object, you can partially emulate the behavior of “multiple inheritance”, but there’s no direct way to handle collisions if the same method or property is being copied from more than one source. Some developers/libraries have come up with “late binding” techniques and other exotic work-arounds, but fundamentally these “tricks” are usually more effort (and lesser performance!) than the pay-off.

Take care only to use explicit mixins where it actually helps make more readable code, and avoid the pattern if you find it making code that’s harder to trace, or if you find it creates unnecessary or unwieldy dependencies between objects.

If it starts to get harder to properly use mixins than before you used them, you should probably stop using mixins. In fact, if you have to use a complex library/utility to work out all these details, it might be a sign that you’re going about it the harder way, perhaps unnecessarily. In Chapter 6, we’ll try to distill a simpler way that accomplishes the desired outcomes without all the fuss.

Parasitic Inheritance

A variation on this explicit mixin pattern, which is both in some ways explicit and in other ways implicit, is called “parasitic inheritance”, popularized mainly by Douglas Crockford.

Here’s how it can work:

  1. // "Traditional JS Class" `Vehicle`
  2. function Vehicle() {
  3. this.engines = 1;
  4. }
  5. Vehicle.prototype.ignition = function() {
  6. console.log( "Turning on my engine." );
  7. };
  8. Vehicle.prototype.drive = function() {
  9. this.ignition();
  10. console.log( "Steering and moving forward!" );
  11. };
  12. // "Parasitic Class" `Car`
  13. function Car() {
  14. // first, `car` is a `Vehicle`
  15. var car = new Vehicle();
  16. // now, let's modify our `car` to specialize it
  17. car.wheels = 4;
  18. // save a privileged reference to `Vehicle::drive()`
  19. var vehDrive = car.drive;
  20. // override `Vehicle::drive()`
  21. car.drive = function() {
  22. vehDrive.call( this );
  23. console.log( "Rolling on all " + this.wheels + " wheels!" );
  24. };
  25. return car;
  26. }
  27. var myCar = new Car();
  28. myCar.drive();
  29. // Turning on my engine.
  30. // Steering and moving forward!
  31. // Rolling on all 4 wheels!

As you can see, we initially make a copy of the definition from the Vehicle “parent class” (object), then mixin our “child class” (object) definition (preserving privileged parent-class references as needed), and pass off this composed object car as our child instance.

Note: when we call new Car(), a new object is created and referenced by Cars this reference (see Chapter 2). But since we don’t use that object, and instead return our own car object, the initially created object is just discarded. So, Car() could be called without the new keyword, and the functionality above would be identical, but without the wasted object creation/garbage-collection.

Implicit Mixins

Implicit mixins are closely related to explicit pseudo-polymorphism as explained previously. As such, they come with the same caveats and warnings.

Consider this code:

  1. var Something = {
  2. cool: function() {
  3. this.greeting = "Hello World";
  4. this.count = this.count ? this.count + 1 : 1;
  5. }
  6. };
  7. Something.cool();
  8. Something.greeting; // "Hello World"
  9. Something.count; // 1
  10. var Another = {
  11. cool: function() {
  12. // implicit mixin of `Something` to `Another`
  13. Something.cool.call( this );
  14. }
  15. };
  16. Another.cool();
  17. Another.greeting; // "Hello World"
  18. Another.count; // 1 (not shared state with `Something`)

With Something.cool.call( this ), which can happen either in a “constructor” call (most common) or in a method call (shown here), we essentially “borrow” the function Something.cool() and call it in the context of Another (via its this binding; see Chapter 2) instead of Something. The end result is that the assignments that Something.cool() makes are applied against the Another object rather than the Something object.

So, it is said that we “mixed in” Somethings behavior with (or into) Another.

While this sort of technique seems to take useful advantage of this rebinding functionality, it is the brittle Something.cool.call( this ) call, which cannot be made into a relative (and thus more flexible) reference, that you should heed with caution. Generally, avoid such constructs where possible to keep cleaner and more maintainable code.