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().

Object.setPrototypeOf() Method JavaScript

There are two camps in JavaScript, one who uses function constructors to create objects and one who directly uses object literals. In JavaScript, function constructors can be extended by using the Object.create() method. This method lets you set prototype of one object to another object.

Constructor2.prototype = Object.create(Constructor1.prototype);

Extending Object Literals

Object literals don’t have prototype property. So, if you want to inherit properties of one literal to another, you can do it several ways. Prior to ES2015, you had to write your own extend method that would copy methods from one object to another. ES2015 introduced few new methods that makes this process easier. The setPrototypeOf() method is one of such methods.

Syntax

Object.setPrototypeOf(targetObj, sourceObj);

Here, targetObj is what you are setting prototype to from sourceObj. This method essentially sets a reference to sourceObj’s methods to targetObj’s __proto__. To understand the utility of this, let’s take two objects, toyota and camry. toyota has a drive() method. Setting the camry’s prototype to toyota makes toyota’s drive() method automatically available to camry. This is done by setting its reference in camry’s __proto__ property.


let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  wifi() {
    return 'using wifi';
  }
}

// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);

console.dir(camry); //prints the camry object
console.log(camry.wifi()); // using wifi
console.log(camry.drive()); // driving toyota

Object.setPrototypeOf()

If you inspect the camry object, you can view the __proto__ property and the reference to the drive() method of toyota. Since the setPrototypeOf() method sets a reference, any changes to toyota’s properties is automatically accessible to camry.

let toyota = {
  drive() {
    return 'driving toyota';
  }
};

let camry = {
  wifi() {
    return 'camry';
  }
};

// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);

// Add a new Method to toyota object
toyota.newMethod = function() {
  return 'new method from toyota';
};

console.log(camry.newMethod()); // Prints 'new method from toyota' 



If you have a method with the same name in both the targetObject and the SourceObject, the method in the targetObject would have higher precedence. This is because javaScript first looks for object’s own method before looking into it’s prototype.

let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  drive() {
   return 'driving camry';
  }
}

Object.setPrototypeOf(camry, toyota);
console.dir(camry.drive()); // logs "driving camry"

Super keyword

You can call the method of the sourceObject from the targetObject’s method by using the super keyword.

let toyota = {
  drive() {
    return 'driving toyota';
  }
}

let camry = {
  drive() {
   return `${super.drive()} camry`;
  }
}

Object.setPrototypeOf(camry, toyota);
console.dir(camry.drive()); // logs "driving toyota camry"

Avoid setting __proto__ manually

Prior to ES2015, Object.prototype.__proto__ was used to set the prototype of object literals. You can still use it as shown in the below example. However, it’s not recommended.

let toyota = {
  print() {
    return 'toyota';
  }
}

let camry = {
  printMe() {
    return 'camry';
  }
}

camry.__proto__ = toyota;

console.dir(camry.print());

Object.create method JavaScript

In JavaScript, Prototype inheritance is much easier than you would have imagined. Simply understand the fundamentals, like we always do!

Inheritance in JavaScript is prototype-based. Every constructor has a property called prototype. For more information about the basics of prototypes, click here.

Master constructor object ‘Object’

Object is the master constructor in JavaScript. Don’t forget to take a note of the capitalization of letter ‘O’ in Object. It’s a
function constructor. Directly or indirectly, every object is created by using Object (master object). Since, it is available in the global space, you can access it directly. If you console.dir(Object), you can view all methods that are available to Object. One of the methods is create(). It enables prototypal inheritance in JavaScript.

console.dir(Object);

Object.create Method

Syntax

Object.create(prototypeObject, propertiesObject);

The Object.create method takes two arguments. First argument must be either an object or null. The second argument is optional and used to set properties. These properties are set in object’s prototype.

Creating Objects

const myObject = Object.create(Object.prototype);
console.dir(myObject);

In the above example, the myObject object is created by using Object’s prototype. This means myObject’s creator is Object.prototype. If you inspect myObject, you can view the following:
Inspecting Object
myObject does not contain anything. However, its __proto__ property is a reference to the Object’s prototype. Hence, you can call methods on myObject that are available in Object’s prototype. If you create an object literal by using const myLiteral = {};, it possesses the same __proto__ because internally every object’s __proto__ is set to Object.prototype.To create an object without setting its __proto__ reference to Object.prototype, pass null as an argument. To verify this, inspect the object. As shown in the image below, it does not contain __proto__ property.

const myObject = Object.create(null);
console.dir(myObject);

Object.create(null)

The Object.create() method also creates objects from constructors. It is similar to using the new keyword. The only difference is that by using the new keyword, you can run the constructor. Hence, it will set the initial properties in the constructor. Whereas, the Object.create() method doesn’t run the constructor and hence the initial properties are not set.

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

let car1 = new Car('red');
let car2 = Object.create(Car.prototype);

console.dir(car1);
console.dir(car2);

New vs Object.create

Extending a Constructor

The main use of the Object.create() method is to extend the constructor. This means that you can inherit methods from a constructor’s prototype properties to other constructors. To extend a constructor, set a prototype reference of one object to another by using the Object.create() method.
Note: Only the constructor’s prototype is inherited and not the constructor.

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

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

const ToyCar = function() {};

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();

console.log(legoCar);

Object.create



Verifying Prototype

In the above example, ToyCar’s __proto__ is set to Car and Car’s __proto__ is set to Object. The isPrototypeOf method verifies if legoCar, which is originally created by using the ToyCar constructor, is a prototype of ToyCar, Car and Object. The instanceof operator also performs the similar task.

const Car = function() {};
const ToyCar = function() {};

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();

// Using the isPrototypeOf method
console.log(ToyCar.prototype.isPrototypeOf(legoCar)); //true
console.log(Car.prototype.isPrototypeOf(legoCar)); //true
console.log(Object.prototype.isPrototypeOf(legoCar)); //true

// Using the instanceof operator
console.log(legoCar instanceof ToyCar); //true
console.log(legoCar instanceof Car); //true
console.log(legoCar instanceof Object); //true

Conclusion

In the classical inheritance, you can create a subClass from a superClass. The subClass inherits all methods of the superClass. In JavaScript, a subConstructor inherits all methods from a superConstructor by using the Object.create method. Contrary to the classical inheritance, where methods of superClass are copied to subClass, JavaScript uses a prototype reference to access methods from the superConstructor.

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.