Scroll to top

JavaScript Class

Class

Class is an object oriented programming concept, in JavaScript it’s similar to a function. Classes are just a special functions added to the ES6. But they give you more power and flexibility by assigning properties to them.

class MyClass {
   …
}

Constructor

A special method that represents class. It is used to create and initialize the object created with a class.

class MyClass {
    constructor() {
        this.myName = 'Sandy';
    }
}

let myClass = new MyClass();
console.log(myClass.myName);     // Sandy

Constructor function can also have arguments to represent class with default values when instantiated.

class MyClass {
    constructor(name) {
        this.myName = name;
    }
}
let myClass = new MyClass('Tanu');
console.log(myClass.myName);     // Tanu

Note: You can choose to not declare a constructor function for a class. There is a default constructor for every class declaration.

class MyClass {
    …
}

MyClass class has default constructor as below.

constructor() {}

Getters and Setters

AKA accessor methods, used to compute the values of properties of a class. These methods are basically prefixed by keywords get and set respectively.

class MyClass {
    constructor() {
        this.myName = 'Sandy';
    }
    get name() {
        return this.myName;
    }
    set name(newName) {
        this.myName = newName;
    }
}

let myClass = new MyClass();
console.log(myClass.name);     // Sandy
myClass.name = 'Tanu';
console.log(myClass.name);     // Tanu

Did you notice? These methods can be called without using parenthesis like a normal function call, this happens because of get and set keywords used before function names.

Computed Method names

Methods and Properties inside the class can be defined with expressions. Ex. The name stored in a literal.

let functionName = 'myFunction';
class MyClass {
    [functionName]() {
        return 'Hi, I am a myFunction';
    }
}

let myClass = new MyClass();
console.log(myClass.myFunction());     // Hi, I am a myFunction 

Class Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Class declarations are not hoisted like JavaScript variables and functions. Lets understand this with the help of an example below.

Function Hoisting in JS:

getMyName();    // Sandy
function getMyName() {
    console.log('Sandy');
} 

If you have already noticed, the getMyName function is called before it’s declaration. This does not give you an error because of JavaScript hoisting. But if you will not e able to do the same thing with JavaScript classes. Lets see with the example below.

Class Hoisting in JS:

new MyClass();     // ReferenceError
class MyClass { … }

With the fact that JavaScript functions are hoisted, classes are are not hoisted even if they are instantiated inside a function.

function myFunction() {
    new MyClass();     // ReferenceError
}

myFunction();     // ReferenceError
class MyClass {}
myFunction();     // OK

Class expressions

Like functions, classes can also be used as an expression. There are two ways to define a class, class declaration and class expression. The one we learn so far is a class declarations, now lets explore class expression.

let myClassLiteral = class MyClass {
    name() {
        return 'Hi, I am a Sandy';
    }
}

let myClassInstance = new myClassLiteral();
console.log(myClassInstance.name());     // Hi, I am a Sandy

But if you try to create an instance of myClass it will give you a ReferenceError.

let myClassInstance = new MyClass();     // ReferenceError: MyClass is not defined

And hence, like function expressions, class expressions can be anonymous.

let myClass = class {
    name() {
        return 'Hi, I am a Sandy';
    }
}

let myClassInstance = new myClass();
console.log(myClassInstance.name());     // Hi, I am a Sandy

Note: Class name (MyClass) in class expression does not matter unless you try to use it inside class. Yes, you heard it right we can access class name inside it.

let myClassLiteral = class MyClass {
    name() {
        return MyClass.name;
    }
}

let myClassInstance = new myClassLiteral();
console.log(myClassInstance.name());     // MyClass

Subclass (Derived class)

A class can be derived from other class with extends clause. All you need to do is to call the base class’s constructor (super constructor) from your derived class. Since the base class’s constructor is called as a super constructor, it can be called with super(). You got it right, super represents your base class and hence you can use it not only to call its constructor but you can also access the members of the class. You can not derive a class without calling a super(). Yeah you heard it right, it will give you an error.

class ParentClass {
    constructor(name, surname) {
	this.parentName = name;
	this.surname = surname;
    }

    getParentName() {
	return this.parentName + ' ' + this.surname;
    }
}

class ChildClass extends ParentClass {
    constructor(childName, parentName, surname) {
	super(parentName, surname);
	this.childName = childName;
    }

    getChildName() {
	return this.childName + ' ' + super.getParentName();	// Reference line A
    }
}

// Instantiate ChildClass
let child = new ChildClass('Sandip', 'Subhash', 'Salunke');

// Access properties of child and parent class
console.log(child.childName);	// Sandip
console.log(child.parentName);	// Subhash
console.log(child.surname);	// Salunke

// Call member functions of child and parent class
console.log(child.getChildName());	// Sandip Subhash Salunke
console.log(child.getParentName());	// Subhash SalunkeI

Notice, how super is used to call base class member function getParentName at Reference line A above. Now you might be thinking that the same could have also be done through this.getParentName() instead of super.getParentName(). That’s true we can do that as well, since a child class is derived from parent class, it can directly access its parent class’s functions. wait, but what if a child class has the function with same name? Here it comes a difference, we have to use static to call parent class’s function.

class ParentClass {
    constructor(name, surname) {
	this.parentName = name;
	this.surname = surname;
    }

    getParentName() {
	return this.parentName + ' ' + this.surname;
    }
}

class ChildClass extends ParentClass {
    constructor(childName, parentName, surname) {
	super(parentName, surname);
	this.childName = childName;
    }

    getParentName() {
	return 'Sombody Salunke';
    }

    getChildName() {
	return this.childName + ' ' + this.getParentName();	// Reference line A
    }
}

let child = new ChildClass('Sandip', 'Subhash', 'Salunke');
console.log(child.getChildName());	// Sandip Sombody Salunke

Note: Reference line A, called this.getParentName() and that’s a child class’s local function. Hence child.getParentName() returned child name as “Sandip Sombody Salunke” instead of “Sandip Subhash Salunke“. Try changing this.getParentName() to super.getParentName() and execute the code again. Great seems like you got the correct child name now.

The prototype of a subclass is the superclass, this is all because we extend the base class. The purpose of prototype is to extend the behavior of an object by adding more things to it, and access them in all of its instances created.

Object.getPrototypeOf(ChildClass) === ParentClass;	// true

Interesting, but this is true only for immidiate parent of a subclass. If you derive a class from derived class, then its prototype would be superclass and not super-superclass.

class GrandChildClass extends ChildClass {
    // ...
}

Object.getPrototypeOf(GrandChildClass) === ChildClass;		// true
Object.getPrototypeOf(GrandChildClass) === ParentClass;		// false

We can extend the built-in classes of JavaScript, but its not recommended to do so. It’s often better to create your own class to control its interface.

class Stack extends Array {
    get topElement() {
        return this[this.length - 1];
    }
}

var stack = new Stack();
stack.push('world');
stack.push('hello');
console.log(stack.topElement); 	// hello
console.log(stack.length); 	// 2

Class is a ECMAScript standard, added in ES6. Most of the concepts demonstrated in this tutorial are ES6 features, like super, constructor, getter & setter, Computed methods & property names etc.

Congratulations!
Today you learn JavaScript Class and it’s basics. I hope you will now be able to use classes in your real life.
Like and comment to encourage me..!!

You may also like to read my other articles.

Create simple chat application using NodeJs, ExpressJs and Socket.io
Chatbox: A Peer to Peet chat application
Design Multithreaded Architecture

Author avatar
Sandip Salunke
I am an IT Professional with 8 Yrs of experience, skills and enormous interest in Software Architecture and Development.

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.