JavaScript Class Tutorial – Features, ECMA Script 5, Expression

In many of our JavaScript tutorials, we have heard of “JavaScript classes” multiple times. In this JavaScript tutorial, we are going to explore JavaScript Class; here, we will see the methods and expression of JavaScript classes with examples.

Learn JavaScript Class with Example

What is JavaScript Class?

A JavaScript class is a type of function. Classes are declared with the class keyword. We can use class expression syntax to initialize the class.

Example-

const y =class{}

How to define a class in JavaScript?

We can define a class with the following syntax of JavaScript.

// Initialising a class definition
    Class Hero {
      constructor(name, level) {
      this.name = name;
      this. level = level;
    }
}

We know that a constructor function is meant to be an object by the capitalization of the first letter.

The class keyword communicates in a more straight forward manner in the objective of our function. The only difference in the syntax of the initialization is using the class keyword of function and assigning the properties inside a constructor() method.

How to Add Method in JavaScript Class?

With class syntax, methods can be directly added to the class in JavaScript.

Example-

class Hero {
   constructor(name, level) {
       this.name = name;
       this.level = level;
}
// adding a method to the constructor
greet() {
     return `${this.name} says hello1`;
   }
   }

Here, we create a new instance of Hello using the new keyword and assigns more values.

Example

const hero1 = new (‘varg ‘ ,1);

How to Extend a JavaScript Class?

An advantageous feature of a JavaScript class is that it can be extended into a new object. This prevents repetitions of code for objects that are similar but need some additional or more specific features.

With ES6 classes, the super keyword is used in the place of a call to access the parent function. We will use Extend to refer to the parent class.

Example-

// creating a new class from parent
  Class Mage Extends Hero {
        constructor( name, level, spell) {
     // chain constructor with super
     super(name, level);
    // add a new property
    this.spell = spell;
}
}

Now, we will see how to create a new Mage instance.

Example

const Hero2 = new mage(‘legon ‘, 2 , ‘Magic Missile’);

Output: Mage {name: “legon”, level:2, spell: ‘Magic Missile ‘ }

Example for initialization, adding methods, inheritance in a class

// Initialise a class
   Class Hero {
     constructor(name, level) {
        this.name = name;
        this. level = level;
}
// Adding a method to the constructor
  greet() {
      return `${this.name`} says hello`;
}
}
//creating a new class from the parent
Class Mage Extends Hero {
   constructor(name, level, spell) {
   // chain constructor with super
Super(name, level);
//add a new property
   this.spell = spell;
}
}

Do you know the Architecture of JavaScript?

JavaScript Class in ECMA Script 5

ECMA Script 5 does not support class type and it also does not support a full object-oriented programming concept as other languages like Java or C#. However, you can create a function in such a way so that it will act as a class.

The following example shows how a function can be used as a class in JavaScript.

Example- 

class in JavaScript
function Person() {
     this.firstName = “unknown”;
    this.LastName = “unknown”;
}
var person1 = new Person();
person1.firstName = “Steve”;
person1.lastName = “Jobs”;
alert( person1.firstName + “ “ +person1.lastName);
var person2 = new Person();
person2.firstName = “Bill”;
person2.lastName = “Gates”;
alert ( person2. firstName + “ “ +person2.lastName);

In the above example, a Person() function includes firstName, lastName, and age variables using this keyword. These variables will act like properties. We know that we can create an object of any function using the new keyword. So, Person1 object is created using the new keyword. So, now Person will act as a class and person 1 and person2 will be its objects. Each object will hold their values separately. All the variables are defined with this keyword which binds them to a particular object when we create an object using the new keyword. So, this is how a function can be used as a class in JavaScript.

Features of JavaScript Class

These are some features of JavaScript Classes:

1. Constructors

Constructors is a special function in the class declaration, which defines a function, that represents the class itself. A constructor will be called automatically when a new instance is created.

Ex: let car = new Vehicle(“Honda”, “Accord”, “Purple”);

A constructor can us super keyword to call the constructor of the class it is extending from.

Also, see – 10 Major Applications of JavaScript

2. Static Method

Static methods are functioning on the class itself and not on the prototype, unlike other methods in the class, which defined on a prototype.

They are declared using static keyword. They are called without creating the instances of the class.

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

Example

class Point {
   Constructor (x, y) {
      this.x = x;
      this. y = y;
}
static distance(a, b) {
    const dx = a.x – b.x;
    const dy = a.y – b.y;
return Math.hypot(dx,dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(Point distance(p1, p2));
}

3. Getters/ Setters

A Class can also have getters/setters to get the property value and or to set the property value.

Example –

class Vehicle {
    constructor (model) {
      this.model = model;
}
get model () {
   return this._model;
set model(value) {
   this._model = value;
}
}

General information about JavaScript

  • Class methods are non-enumerable. A flag will be set to false for all the methods defined on its prototype. If you don’t add a constructor to a class, a default constructor will be added automatically.
  • A code will be always in a strict manner and this helps to write error-free code, by throwing errors, on mis-typing or syntactical errors done while writing code or even removing some code by mistake, while is referenced from somewhere else.
  • Class declarations are not hoisted. Hoisting in JavaScript is behavior in which all the declarations are automatically moved on top of the current scope, this behavior actually lets you use a variable or a function before its declared.
  • So, the class declaration is not hoisted means, you cant use a class before it is declared. It will return a not defined error.
  • JavaScript Classes doesn’t allow the property value assignments like constructors, functions or object literals. You can only have functions or getters/ setters.

JavaScript Class Expression

A class expression is another way to define a class. A class expression can be named or unnamed. The class given to a named Class Expression is local to the class’s body( it can be retrieved through the classes (not an instance) name property.

Example-

//named
let Rectangle = class {
  constructor(height, width) {
     this.height = height;
  this. width =width;
}
};
console.log(Rectangle.name);
//output : “Rectangle
//named
let Rectangle = class Rectangle2 (
    constructor( height, width) {
      this.height =height;
      this.width = width;
}
};

Prototype Method

Refer to this example to understand the prototype method in JavaScript Class

class Rectangle {
   constructor(height,width) {
       this.height = height;
       this.width = width;
}
//getter

get area() {
     return this.CalArea();

}
//Method
calcArea() {
     return this.height *this.width;
  }
  }
Const square = new Rectangle(10, 10);
Console.log(square.area);

Summary

Hence, we learn all about JavaScript classes and their features. Also, we covered how to define, expression and extend classes in JavaScript with examples. Hope, you liked our explanation. You may know the latest career opportunities for JavaScript.

Feel free to share your queries and suggestions!

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.