Mixins In JavaScript

What is a Mixin?

Original concept of mixin came from an ice cream shop that provided on-demand customizable ice cream. At these shops, customers can make their own flavor by mixing up different toppings. You would pick up an ice cream flavor and a bunch of toppings, and then you can choose to mix them inside the ice cream by smashing these together instead of sprinkling as a topping. Hence, these are called mixins.

In terms of programming, Mixins are these pieces of code that you can mix with other objects to extend their functionality. Basically, you can borrow features from different mixins to compose the kind of object you desire.


Inheritance vs Composition

By using mixins, you can compose objects with a desired functionality. This is very different from using inheritance, which is much rigid and doesn’t work most of the time when you want to create dynamic ever-changing models. For example, you want to build a class called javaScriptEngineer, where javaScript means you can code in JavaScript and related technologies and Engineer means you have some sort of Engineering degree. Instead of using inheritance, where you would create an engineer class and extend it to make a JavaScript engineer, you can separate out both the functionalities into a separate mixins. You can compose javaScriptEngineer by using the Object.assign() method where you can borrow methods from two different mixins.

Composing Object using Mixins

In the following example, we have two objects jsSkill and degree, they both would serve as mixins when I combine their properties and copy into an empty object using the Object.assign() method. The newly created object jsEngineer will have functionality of jsSkill and degree. Similarly, you can create a fullstackEngineer by using one more mixin. Since Fullstack engineer knows JavaScript, has an engineering degree, and also knows one or more backend languages, we just need to add an additional backendSkill mixin. This allows us to compose a fullstackEngineer.

Factory Functions

Factory functions are functions that produces objects. In JavaScript, there are two ways to create objects, one by using either function constructors or classes. In either case, you have to use a new keyword. And secondly, by using regular functions. When you use regular functions to build objects, they are called factory functions. Following example describes a factory function.

Factory Function with closures

Having an inner variable inside the factory function will maintain the state inside a closure. The state will be stored inside every function that is using the variable.

Function Mixins

Using a factory function with closures you can build function mixins. Each mixin would take an Object as a parameter and returns a new object that would take passed object and extend it with mixin’s functionality. Here is an example of building an object called superman using two mixins humanFactory and flyFactory. superman has characteristics of a human so he has an ability to cry, however unlike humans, he can fly. So, combining two different kind of abilities we can transform an ordinary reporter clark kent into the superman.

Note: When you pass an empty object to this factory, the returning Object would have a functionality of humanfactory, flyFactory and their preserved states.

Conclusion

function mixin is one of the functional programming paradigm . Mixins help you reduce repetition of functions and promotes the reusability. This can reduce maintenance. It also support encapsulation using closures, with ability to inherit private data. In a way you can sort of achieve multiple inheritance since can inherit from multiple mixins. In this article, we discussed function mixins for a functional programming paradigm. The same concept also applies to ES2015 classes with a difference in syntax. To understand mixin for ES2015 classes, click here -> (class mixins coming soon).

JavaScript Classes

Class Keyword

JavaScript uses the class keyword, which was introduced in ES2015. Prior to ES2015, you can create objects by using function constructors and prototype inheritance. There are many developers who believe that classes do not belong to JavaScript. They consider JavaScript as a functional programming language. I have heard opinions from the other side of the isle, where they believe that classes provide a less complicated solution. So regardless of an individual’s belief, classes are here! They are here to stay and are used extensively in modern frameworks like Angular, React, and Ember. Before we go deep into classes, let’s understand what does a class mean to JavaScript.

Feels like Classes, Smells like Classes!

Introduction to classes in JavaScript was a great news for some, especially, former Java programmers who will feel like home. I believe, objective of people who added classes was just the same. However, I think a Java programmer will be more confused because under the hood classes do not act the same way as they do in Java. To quote a simple analogy, it’s like when you want your kids to eat more vegetables, you make a pizza, substitute tofu for cheese and spinach for pepperoni. Though you hide spinach in the middle layer, your kids can recognize that this is not a real pizza in their very first bite! Java programmers may feel the same as classes in JavaScript internally use the same function constructor and prototype methods from the versions prior to ES2015. Said that, syntactically classes are defined in the similar way as they are defined in Java.

Syntax

In the example bellow, we have defined class Car. Notice the difference between the function declaration and class declaration? While declaring a class, we do not use semicolon. Similarly, to define a constructor, use the keyword ‘constructor’ and add the parameters to set the initial properties. If you check the type of the class you will be surprised that it’s actually “function” not “class”.

 Inspecting  a JavaScript Class
Inspecting a JavaScript Class

If you inspect the newCar object in detail you would see similar structure when you create object with function constructor. The only difference is that the constructor displays the keyword “class”.



Simulating Class with Function Constructor

You can simulate the class behaviour using a function constructor wrapped inside an Immediately Invoked Function Expression (IIFE). This is obviously to see what is going on inside when you define a class.

Inspecting Function Constructor
Inspecting Function Constructor

Adding Methods

Now let’s add a drive() method to class Car. Note that there is no comma between two methods. It feels weird if all you have used is JSON Objects.

Inspecting Class Method
Inspecting Class Method

When you inspect the class Car, you would notice the prototype property. Expanding prototype property displays the drive method. This means that Car is actually a function and drive is its prototype methods. Sounds familiar ? :). As I said, Class keyword is nothing but what some call “syntactic sugar”. All the methods are public. Unlike java, JavaScript doesn’t provide a way to add private methods.

Next, let’s build objects from class Car. The syntax is similar to what we used with function constructors, using the new keyword. You can execute the method on this object by calling redCar.drive().

JavaScript Prototype Explained

Every constructor function has a property called prototype. You can add properties and methods to it. Using a constructor function, When you create a new object, the object has access to prototype methods.

Sample code:

let Car = function(color) {
 this.color = color;
};

Car.prototype.getColor = function() {
 return this.color;
};

let redCar = new Car('red');

console.dir(redCar);

If you inspect the redCar object, you will see the following.Inspect ObjectIn the above image, the getColor() is not a part of the redCar object. There is another property called __proto__, which is set automatically. You can think of __proto__ as the creator of redCar. If you expand __proto__, the getColor method and the constructor are displayed. Constructor is the a reference to the Car Constructor that created redCar.
__proto__ property If you expand the Car constructor, the prototype property of the constructor is displayed. If you further expand the prototype property, the getColor method is displayed.

ProtoType Property JavaScriptThe getColor method from __proto__ is actually a reference to the one you added to the constructor’s prototype. It looks tricky, however, all you care about is that __proto__, the creator of redCar, has the getColor method. Hence, when you call the redCar.getColor() method, JavaScript will look inside the redCar object. If the method doesn’t exist in the object, it will look for the method in the object’s creator, which is __proto__. It will find it and execute it.
JavaScript Master ObjectSo, let’s analyze a little more and discover how is __proto__ created. If you further expand __proto__, you will see its creator, which is the master __proto__. This is basically a master object called Object (the letter ‘O’ is capitalized). Every object in JavaScript is created from Object. It also has some methods. One of the methods is toString(). When you call this method on redCar, JavaScript will first search for this method in the redCar object. If it can’t find it there, it keeps searching for the method all the way to the end of the prototype chain.




There are pros and cons of using prototype inheritance. The best part is, the inheritance makes objects lighter. The drawback is that every time you call a method that is not a part of the object, it looks for the method up the prototype chain. Hence, it makes it a little slower. The workaround is, if you are going to call this method frequently, store it in a variable to avoid the lookup.

let toString = Object.toString;
console.log(redCar.toString());

Overwriting Object Methods

If you want to customize the toString() method, you can add it to the object’s prototype. However, there are times when you want to make method available to every object. In such case, add it to the master object’s prototype. This would shadow the native toString() method.

Object.prototype.toString = function(){
    return `color:${this.color}`;
};

let Car = function(color) {
  this.color = color;
};

Car.prototype.getColor = function() {
  return color;
};

let redCar = new Car('red');


console.dir(redCar.toString());

In next article, I will show you how to use Object.create() method to set prototype of one object to another. Follow the link below. Object.create() method

JavaScript Function Constructors

It is very important to understand how JavaScript function constructors work before we move to higher level topics of Object Oriented JavaScript. In this article, I am not going to explain about the JavaScript class constructor. Instead, I’ll explain about ‘function’ constructors.
The ultimate objective of Object Orient Programming is to create objects with ease. Languages like Java have classes and each class can have a constructor, and its job is to set initial properties of the object. In JavaScript, you can create an object by directly using constructors. JavaScript lets you use a function as a constructor, if called in a specific way. And, that’s what this entire article is all about!

Usually, the job of a function is to run a specific job. Let’s say, I want to add two numbers. will write a function that takes two arguments and return the addition of the two numbers.

Sample of a function for adding two numbers:

let add = function(number1, number2) {
 return number1 + number2;
};

let sum = add(1, 2);

Now, let’s look at an example of a function constructor.

let Car = function(color) {
 this.color = color;
};

let redCar = new Car('red');

As shown in the above example, a regular function takes arguments. It performs an action within the body of the function and returns the result. A regular function may or may not return anything.
Function constructor, on the other hand, accepts color as an argument and sets it to its this.The constructor function does not contain a return statement. Instead, it returns a new object with the property that is passed as an argument.

The basic syntax difference for executing a regular function and a constructor function is the usage of the new keyword.

If you were to manually create an object without using the constructor function, the syntax will look like following:

let redCar = {
 color: 'red'
};

If you inspect the newly created object in a browser, this is how it would look like:


JavaScript function constructor inspect

As you can notice, it has a color property which is set to ‘red’; The property, __proto__, is its creator. If you expand the __proto__, you will see the following:

JavaScript function constructor inspect

The reference to the constructor that set the initial property is the Car constructor that you used to create redCar.

Drawbacks of not using new

Now, let’s consider a scenario where you execute a constructor function as a regular function without using the keyword ‘new’.

let Car = function(color) {
  this.color = color;
};

let redCar = Car('red');

In this case, this.color = color will create a new property color in the global space. You can verify the result by using console.log(window.color);

To prevent such error, add se use strict, which throws the following exception:

error calling function constructor without 'new' keyword

You can also use the new.target to throw a customized error message..

let Car = function(color) {
  if (!new.target) throw 'Car() must be called with new';
  this.color = color;
};

let redCar = new Car('red');

Private Vs Public properties

In JavaScript, all object properties are public, which means you can access it directly. For example, redCar.color. JavaScript does not have a native support for private property. Private properties are the properties you cannot access directly by using a dot notation. However, you can call a getter or have a getter method like getColor to access it and use closure.

let Car = function(_color) {
  this.setColor = function(color){
    _color = color;
  }
  this.getColor = function() {
    return _color;
  };
};

let redCar = new Car('red');

console.log(redColor.getColor());

Here _color is a private variable that cannot be accessed by the object using redCar._color.
Since it is a closure, the methods have access to them.

Adding methods to a Constructor

Best way to have methods is to set methods in prototype space. For more information about settings methods in the prototype space, go to Prototype.