How to create a Class in JavaScript

Have they ever asked you that “How you create class in JavaScript?” I am sure, regardless level of JavaScript interview; you must have come across this question. Well, there is no one answer of this question. However, before you go ahead and read detailed answer in this post, let me give you a gist in two bullet points,

  1. In ECMA 6, class can be created using the keyword class
  2. In earlier version like ECMA 5, calling a function using the new operator returns an object. So you can say , “when we call a function using the new operator (which is also known as ‘constructor invocation pattern’), function acts like a class and returns a newly created object ”

Class in ECMA 6

In ECMA 6, you can create a Student class as shown in the listing below:


class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
getData() {
console.log(this.name + " is " + this.age + " years old !");
}
}

view raw

classinjs1.js

hosted with ❤ by GitHub

ECMA 6 allows you to create a class using the keyword “class”. You can create object of Student class using the new operator as shown in the listing below:


var s1 = new Student("foo", 7);
var s2 = new Student("bar", 9);
s1.getData();
s2.getData();

view raw

classinjs2.js

hosted with ❤ by GitHub

Like function declaration and expression, class can also be created

  1. Class declaration
  2. Class expression

image

Above, you created Student class using the class declaration syntax. Same Student class can be created using the class expression syntax as shown in the listing below:


var Student = class {
constructor(name, age) {
this.name = name;
this.age = age;
}
getData() {
console.log(this.name + " is " + this.age + " years old !");
}
toString() {
return `(${this.name},${this.age})`;
}
}

view raw

classinjs3.js

hosted with ❤ by GitHub

Above, you created Student class using the class unnamed expression syntax. Same Student class can be created using named class named expressions syntax as shown in the listing below:


var Student = class s {
constructor(name, age) {
this.name = name;
this.age = age;
}
getData() {
console.log(this.name + " is " + this.age + " years old !");
}
toString() {
return `(${this.name},${this.age})`;
}
}

view raw

classinjs4.js

hosted with ❤ by GitHub

Keep in mind that name given to class expression is local to the class body.

Hoisting of the class

Did you remember that functions declaration is hoisted? Means, you can call a function declaration before it is created.


foo();
function foo() {
console.log("I am hoisted");
}

view raw

classinjs5.js

hosted with ❤ by GitHub

In above listing you declared a function and that is hoisted, so you are able to execute it before it is created. However, class are not hoisted in JavaScript. Does not matter whether you are creating a class as declaration or expressions, they are not hoisted. So if you do something as shown in below listing


var s1 = new Student("foo", 7);
var s2 = new Student("bar", 9);
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

view raw

classinjs6.js

hosted with ❤ by GitHub

On running above code will throw you ReferenceError exception.

image

Therefore, conclusion is unlikely JavaScript functions classes are not hoisted.

image

A class can be referred in the function which comes before class declaration. However, you can call such function only after the declaration of the class. Let us consider below code


function printstudent() {
var s1 = new Student("foo", 7);
console.log(s1.name);
}
printstudent(); // Student is not defined error
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
printstudent(); // print foo

view raw

classinjs7.js

hosted with ❤ by GitHub

In above code, first function call will throw reference error, whereas second function call will work fine.

Methods in class

Most often you will create these three types of methods in the class,

  1. Constructor
  2. Static
  3. Prototype

Constructor method

A constructor method is a special method. Constructor method creates and initializes the object created with the class. A class can have only one constructor method. More than one constructor method in the class will throw exception. A class with constructor can be created as shown in the listing below:


class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
}

view raw

classinjs7.js

hosted with ❤ by GitHub

image

Static methods

Like any other programming languages, JavaScript static methods are called without creating the object of the class. You can create a class with static method as shown in the listing below:


class Student {
static LogStudent() {
return "I am static method";
}
}

view raw

classinjs8.js

hosted with ❤ by GitHub

You can call static method with the class name as shown below:


var n = Student.LogStudent();
console.log(n);

view raw

classinjs8.js

hosted with ❤ by GitHub

When you try calling static method with instance of the class, JavaScript will throw exception. As of now JavaScript does not support static members or properties.

image

Prototype methods

JavaScript class prototypes methods are the methods used by the instances of the class. They are the normal methods, which can be inherited and used by the objects.


class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
getData() {
return this.name + " is " + this.age + " years old !";
}
}

view raw

classinjs10.js

hosted with ❤ by GitHub

These prototype methods can be used with instance of the class as shown in the listing below:


var s1 = new Student('foo', 9);
console.log(s1.getData());
var s2 = new Student('bar', 7);
console.log(s2.getData());

view raw

classinjs11.js

hosted with ❤ by GitHub

These prototype properties are actually property of the Student.prototype.

image

In JavaScript, functions have prototype property, and class has prototype property. Because type of class is function. So when you execute below code,


class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
getData() {
return this.name + " is " + this.age + " years old !";
}
}
console.log(typeof (Student));

view raw

classinjs12.js

hosted with ❤ by GitHub

Output of above code would be function.

image

Class in ECMA 5

You do not create class using the class keyword in ECMA 5. If you wish to create same class Student in ECMA 5, create a function with the name Student as shown in the listing below:


function Student(name, age) {
this.name = name;
this.age = age;
}

view raw

classinjs13.js

hosted with ❤ by GitHub

You can add prototype methods as shown in the listing below:


Student.prototype.getData = function () {
return this.name + " is " + this.age + " years old !";
}

view raw

classinjs14.js

hosted with ❤ by GitHub

Now to create objects, call function Student using the new operator as shown in the listing below:


var s1 = new Student("foo", 8);
console.log(s1.getData());
var s2 = new Student("bar", 9);
console.log(s2.getData());

view raw

classinjs16.js

hosted with ❤ by GitHub

Calling a function using the new operator is also called as “Constructor Invocation Pattern”. Therefore, in ECMA 5, when you call a function using the new operator, function acts as a class and returns an object.

Here, you also learnt what constructor invocation pattern is. I hope now you should able to answer

  1. How to create class in ECMA 6
  2. How to create class in ECMA 5
  3. What is Constructor Invocation Pattern

I hope it helps. Thanks for reading.

Leave a comment

Create a website or blog at WordPress.com