Using Classes in JavaScript

javascript class method

Use the keyword class to make a class. A class encapsulates data and functions that manipulate data.

Classes prior to ES6 revisited

 

function Member(name) {
this.name = name;
}

Member.prototype.fetchMemberName = function () {
return this.name;
};

var Mayur = new Member("Mayur Dhameliya");
console.log(Mayur.fetchMemberName());

 

Output
 

Mayur Dhameliya

 

First, make the Member as a constructor function that has a property name called name. The fetchMemberName() function is assigned to the prototype so that it can be shared by all instances of the Member type.

Then, make a new instance of the Member type using the new operator. The Mayur object, hence, is an instance of the Member as well as Object through prototypal inheritance.

The bellow statements use the instanceof operator to check if Mayur is an instance of the Member as well as Object type:

 

console.log(Mayur instanceof Member); // true
console.log(Mayur instanceof Object); // true

 

ES6 class declaration

 

class Member {
constructor(name) {
this.name = name;
}
fetchMemberName() {
return this.name;
}
}

 

This Member class behaves like the Member type in the previous example. However, instead of using a constructor/prototype pattern, it uses the class keyword.

In the Member class, the constructor() is where you can initialize the properties of an instance. JavaScript automatically calls the constructor() method when you instantiate an object of the class.

The bellow makes a new Member object, which will automatically call the constructor() of the Member class:

 

let Mayur = new Member("Mayur Dhameliya");

 

The fetchMemberName() is called a method of the Member class. such as a constructor function, you can call the methods of a class using the bellow syntax:

 

objectName.methodName(args)

 

For example:

 

let name = Mayur.fetchMemberName();
console.log(name); // "Mayur Dhameliya"

 

console.log(typeof Member); // function

 

The Mayur object is also an instance of the Member as well as Object types:

 

console.log(Mayur instanceof Member); // true
console.log(Mayur instanceof Object); // true

 

I hope you get an idea about javascript class method.


 

#javascript 

 Using Classes in JavaScript
1.00 GEEK