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