AppDividend
Latest Code Tutorials

Javascript Class Example | How To Use Class in Javascript Tutorial

0

Javascript Class Example | How To Use Class in Javascript Tutorial is today’s topic. JavaScript is a prototype-based language, and every object in JavaScript has a hidden internal property called [[Prototype]]. JavaScript ECMAScript 5, does not have a class type. So it does not support the full object-oriented programming concept as other programming languages like Java or C#. However, you can create the function in such a way that it will act as a class.

JavaScript ECMAScript 5 Way of Class

In ES5, the Classes are Functions.

Let’s see the following example.

// app.js

function Employee() {
  this.firstName = 'Krunal';
  this.lastName = 'Ankit';
}

var empA = new Employee();
empA.firstName = 'Rushabh';
empA.lastName = 'Dhaval';
          
console.log(empA.firstName + ' ' + empA.lastName);

var empB = new Employee();
empB.firstName = 'Nehal';
empB.lastName = 'Khushbu';

console.log(empB.firstName + ' ' + empB.lastName);

In the above code example, we have created the Employee class in ES5.

An Employee function includes the firstName, lastName variables using this keyword. These variables will act like the properties. As you know, we can create an object of any function using the new keyword, so an empA object is designed with the new keyword. So now, Employee will act as the class, and empA & empB will be its objects (instances).

Each object holds their values separately because all the variables are defined with the help of this keyword, which binds them to the specific object when we create an object using the new keyword. So this is how you can use the function as a class in the JavaScript.

We will run the program on Node.js platform. See the below output.

 

Javascript Class Example

Add Methods in an ES5 Class

We can add the function expression as a member variable in the function in JavaScript. The function expression will act as a method of the class. See the following example.

// app.js

function Employee() {
  this.firstName = 'Krunal';
  this.lastName = 'Ankit';
  this.getFullName = function(){
    return this.firstName + " " + this.lastName;
  }
}

var empA = new Employee();
empA.firstName = 'Rushabh';
empA.lastName = 'Dhaval';        
console.log(empA.getFullName());

var empB = new Employee();
empB.firstName = 'Nehal';
empB.lastName = 'Khushbu';
console.log(empB.getFullName());

In the above example code, we have created the function called getFullName() inside Employee class.

Now, we can call the method using the object using the dot(.) notation. So now, getFullName() will act as a method of the Employee class. We can call the method using dot notation e.g. empA.getFullName().

We will get the exact output as above example.

Constructor in ES5

In the other languages like Java or C#, the class can have one or more constructors. In JavaScript language, a function can have one or more parameters. So, the function with one or more parameters can be used like the constructor where you can pass parameter values at a time or creating the object with a new keyword.

See the following example.

// app.js

function Employee(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.getFullName = function(){
    return this.firstName + " " + this.lastName;
  }
}

var empA = new Employee('Rushabh', 'Dhaval');      
console.log(empA.getFullName());

var empB = new Employee('Nehal', 'Khushbu');
console.log(empB.getFullName());

In the above example, the Employee function includes two parameters firstName and lastName. These parameters are used to set the values of the specific property. The outcome will be the same as the above two examples. We have used the constructor in js to define the initial value of the class.

Javascript Class Example

Now, let’s go to the ES6 style of Class in Javascript. JavaScript classes, introduced in ECMAScript 2015 or ES6, are primarily the syntactical sugar over the JavaScript is an existing prototype-based inheritance. The class syntax does not introduce the new object-oriented inheritance model to JavaScript.

Define a class in Javascript

One way to define the class is by using the class declaration. If we want to declare a class, you use the class keyword with the name of the class (“Employee” here). See the below code.

// app.js

class Employee {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

In the above code, we have defined the class and the constructor, which is parameterized.

A significant difference between function declarations and class declarations is those function declarations are hoisted, and the class declarations are not. You f need to first declare your class and then access it; otherwise, code will throw a ReferenceError.

Class expressions

class expression is another way to define the class.

Class expressions can be named or unnamed.

A name given to the named class expression is local to that class’s body.

See the following code.

// app.js

let Employee = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
console.log(Employee.name);

The above code will output the Employee. The name is the property of Class Employee.

Class body and method definitions

The body of a class is a part that is in the curly brackets {}. This is where you define all the class members, such as methods or constructor.

Strict mode

The body of a class is executed in the strict mode, i.e., code written here is subject to the more stringent syntax for increased performance, some otherwise silent errors will be thrown, and specific keywords are reserved for the future versions of ECMAScript.

Constructor

The constructor method is a unique method for creating and initializing the object created with the class. There can only be one unique method with the name “constructor” in a class. The constructor can use the super keyword to call the constructor of the superclass.

See the following example.

// app.js

class Employee {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  // Getter
  get name() {
    return this.fullName();
  }

  // Method
  fullName() {
    return this.firstName + ' ' + this.lastName;
  }
}

const e1 = new Employee('Krunal', 'Lathiya');
console.log(e1.name);

In the above example, we have created the constructor, getter property, and js method.

Then we have created an object from the class and pass the parameter to the parameterized constructor and then use the getter property to fetch the name from the name() function and then display it to the console.

One thing you note here that we have called the name as a property and not as a method. It is because getter is the property and not the method.

So, in the output, we will get the name in the console. See the below output.

Class body and method definitions

 

Static methods in Javascript Class

The static keyword defines the static method for the class. Static methods are called without the instantiating their class and cannot be called through a class instance. The static methods are often used to create the utility functions for the application.

// app.js

class Employee {
  static power(a, b) {
    return Math.pow(a, b); 
  }
}

console.log(Employee.power(8, 2));

See the below output.

Static methods in Javascript Class

 

Subclassing with extends

The extends keyword is used in the class declarations or class expressions to create a class as a child of the another class. See the following example code.

// app.js

class Person {
  constructor(name) {
    this.name = name;
  }
}

class Employee extends Person {
  constructor(name) {
    super(name); // call the super class constructor and pass in the name parameter
  }
  info() {
    console.log(`The Employee Name is: ${this.name}`);
  }
}

let epl = new Employee('Krunal');
epl.info();

See the output.

How To Use Class in Javascript Tutorial

 

If there is a constructor present in a subclass, it needs to first call super() before using “this.” Note that classes cannot extend the regular (non-constructible) objects. 

Finally, Javascript Class Example | How To Use Class in Javascript Tutorial is over.

Leave A Reply

Your email address will not be published.

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