Understanding Javascript Es6 Classes

Yasemin çidem
Mar 26 · 5 min read

The basic idea of Object Oriented Programming is that we use objects to model real world things that we want to represent inside our programs and/or provide a simple way to access functionality that would otherwise be hard or impossible to make us of. Generally to make this easier, we use class. JavaScript does not have classes, the way that Java and other languages have.

In Javascript classes are nothing but a syntactic sugar over existing prototype based inheritance and constructor functions.

In this article, we will dive into what Classes do behind the scene by comparing it to Prototype based inheritance.

What Es6 classes provide:

  1. Constructor method:
    The constructor method is a special method for creating and initializing an object created with a class. There can only be one constructor method in a class.
//create an object with class keyword
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
var person = new Person('test', 12);
console.log(person);

Constructor function:

//define a constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person('test', 12);
console.log(person);

No matter how we created object through class or constructor function. The object points same properties and methods.

2. Static Methods:

Javascript static methods are generally used to create utility functions. Es6 classes supports static method. To declare a static method in Es6 classes, we can simply use static keyword with the method signature.
The static method are not called on the instance of class they are made to call directly on the class.

class Article {  
constructor(title, date) {
this.title = title;
this.date = date;
}
static createTodays() {
//remember, this = Article
return new this("Today's digest", new Date());
}
}
let article = Article.createTodays();
console.log( article.title ); // Today's digest
console.log( article.date ); // Thu Mar 25 2021 14:19:38 GMT+0300

Static method without using class keyword:

function Article(title, date) {  
this.title = title;
this.date = date;
}
Article.createTodays = function() {
//remember, this = Article
return new this("Today's digest", new Date());
}
let article = Article.createTodays();
console.log( article.title ); // Today's digest
console.log( article.date ); // Thu Mar 25 2021 14:19:38 GMT+0300

3. Getters/Setters:

ECMAScript 5 had introduced Getter and Setters before Es6 added them into the class. Getters and setters allow us to define Object Accessors. Getters and Setters offers us these benefits:

  • It gives simpler syntax
  1. get/set methods inside the class
// inside class
class MyClass {
constructor() {
this.names_ = [];
}

set name(value) {
this.names_.push(value);
}

get name() {
return this.names_[this.names_.length - 1];
}
}

const myClassInstance = new MyClass();
myClassInstance.name = 'Joe';

2. get and set methods inside the function.

// inside function
function MyFunc() {
this.names_ = [];
}
Object.defineProperty(MyFunc.prototype, "name", {
get: function() {
return this.names_[this.names_.length - 1];
},
set: function(value) {
this.names_.push(value);
}
});
const myFuncInstance = new MyFunc();
myFuncInstance.name = 'Joe';

4. Inheritance:
Inheritance is important concept in object oriented programming. In the classical inheritance, methods and properties from base class get copied into derived class.
In JavaScript, inheritance is supported by using prototype object until ES6 came out. Some people call it “Prototypal Inheritance” and some people call it “Behaviour Delegation”. ES6 Class provides us to copy methods and properties from base class into derived class.

class Car {
constructor(brand) {
this.car_name = brand;
}
present() {
return ‘I have a ‘ + this.car_name;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ‘, it is a ‘ + this.model;
}
}
let myCar = new Model(“Ford”, “Mustang”);
console.log(myCar.show()); // I have a Ford, it is a Mustang

Note: super method refers to the parent class. By calling the super method in the constructor method, we call the parent’s constructor method and gets access the parent’s properties and methods.

We can do the same example with prototypes.

function Car(brand) {
this.car_name = brand;
}
Car.prototype.present = function() {
return ‘I have a ‘ + this.car_name;
}
function Model(brand, mod) {
Car.call(this, brand);
this.model = mod;
this.show = function() {
return this.present() + ‘, it is a ‘ + this.model;
}
}
Model.prototype = Object.create(Car.prototype)
let myCar = new Model(“Ford”, “Mustang”);
console.log(myCar.show()); // I have a Ford, it is a Mustang

Factory Function:

Factory function is any function which is not a class or constructor that return an object. In Javascript, any function can return an object. When it does so without the new keyword, it is called factory function . If you need to create many objects, you can combine the power of object literals and factory functions.

  • This is an object that created with object literal:
const user = {
userName,
avatar,
setUserName (userName) {
this.userName = userName;
return this;
}
};
  • We can transform it into factory function to create multiple object from it.
const createUser = ({ userName, avatar }) => ({
userName,
avatar,
setUserName (userName) {
this.userName = userName;
return this;
}
});
console.log(createUser({ userName: 'echo', avatar: 'echo.png' }));

If you don’t want to deal with new keyword, class or prototypes, you can achieve the same functionality with factory function.

In this article, we tried to see the other alternatives of class. Hopefully, it would help you understand the class better and see what happens behind the scene. Also it proves that the classes are nothing but a syntactic sugar over existing prototype based inheritance and constructor functions in Javascript.

Object.create():

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object. Also we can make use of this method to manage the inheritance easily through Object.create method.

Syntax:

Object.create(proto, [propertiesObject])

proto : The object which should be the prototype of the newly-created object.

propertiesObject : It is an optional parameter. It specifies the enumerable properties to be added to the newly created object.

Let’s illustrate below class example with Object.create method.

// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);

//If you don't set Rectangle.prototype.constructor to Rectangle,
//it will take the prototype.constructor of Shape (parent).
//To avoid that, we set the prototype.constructor to Rectangle (child).
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?', rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

We can manage same inheritance with Object.create() .

let myCar = Object.create(null, );

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Yasemin çidem

Written by

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.