JavaScript Classes

Overview

A JavaScript class serves as a blueprint for creating objects. In the realm of JavaScript, classes function as templates that encapsulate both data and the methods required to manipulate that data. Often described as syntactical sugar introduced in ES6, JavaScript classes provide a more refined way to enhance object properties and methods, a task that was previously accomplished using prototypes and inheritance.

Overview of Classes in JavaScript

We encounter data or objects with comparable characteristics on a daily basis. For example, the process of inputting details such as name, class, and roll number onto 100 digital identification cards serves as a practical illustration. This demonstrates the application of objects and classes. In the case of JavaScript, a prototype-based language, object properties and methods are enhanced through the use of a concealed [[Prototype]] property.

Classes made their debut in JavaScript with the introduction of ES6, offering a more concise syntax for creating templates that can be utilized to generate objects. Please note: This tutorial does not necessitate any prior knowledge of classes or earlier ES6 functionalities.

Example

JavaScript Class Syntax
class Classname {
    constructor() { ... }
}

Definition of Syntax:

  • JavaScript classes are created with the class keyword.
  • The class name appears in the Classname. It is determined by the user. The class name is often started with a capital letter.
  • To initialize the properties of an object, use the constructor function. A new instance of the designated class is launched automatically upon creation. (Parameters can be required).
  • Building a Class in JavaScript

We will create a class designed to represent students who are engaged in classroom learning. This class will encompass each student's first name, last name, age, and roll number.

Example

class Student{
    constructor(firstName, lastName, age, rollNo){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.rollNo = rollNo;
    }
}

The "this" keyword in JavaScript refers to the object that is currently being processed within a method or constructor. Its primary function is to resolve any confusion that may arise when class properties and parameters passed to the constructor share identical names.

In the preceding code segment, we are defining a class named Student (it is customary for class names to start with an uppercase letter). The Student class encompasses four attributes: rollNo, age, lastName, and firstName. The constructor function receives four parameters, which it then assigns to the respective attributes of the class.

Note: It should be noted that although the constructor parameters and class attribute names in the aforementioned example are the same, they are not the same.

The inputs provided by the user during the creation of an object, which are utilized to set the class attributes, are referred to as the constructor parameters.

It is a common convention to use similar names for constructor parameters and class attributes, though it is also permissible for them to have different names. For example:

Example

class Student{
    constructor(firstNameInput, lastNameInput, ageInput, rollNoInput){
        firstName = firstNameInput;
        lastName = lastNameInput;
        age = ageInput;
        rollNo = rollNoInput;
    }
}

JavaScript Class types

A specific category of function is represented by a JavaScript class. In the example provided below, the class's type is determined through the utilization of the 'typeof' operator. The result returned is "function," which is illustrated in the output.

Example

<!DOCTYPE html>
<html>
<body>
<p id = "output"> The type of the vehicle class is: </p>
<script>
class Vehicle {
// Class body
}
document.getElementById("output").innerHTML += typeof Vehicle;
</script>
</body>
</html>

Output:

The constructor function

We can set up the object attributes within the function body when utilizing it as a template for an object. Similarly, to assign values to the object properties, it is essential to employ the constructor function in conjunction with the class. Each time we create an instance of the class, the constructor function is automatically called.

In the following example, we create a Vehicle class through the use of the constructor function.

Example

class Vehicle {
	constructor(brand) {// Here we need to Define the constructor
		this.brand = brand;
	}
}

The keyword 'constructor' can be utilized to define the constructor function, which does not have an explicit name. Within the constructor method, the 'this' keyword can be employed to initialize the properties of the class.

Object creation in JavaScript

To instantiate an object from a JavaScript class, it is necessary to use the class identifier, followed by a pair of parentheses, and the new keyword. Additionally, we can provide arguments to the constructor if needed.

We will initiate the process by defining an object referred to as myVehicle.

Example

const myVehicle = new Vehicle("Car");

An object that is executing the current operation is represented by the "this" keyword within the constructor function.

Example: Creating class objects without any parameters

The following example illustrates the definition of the 'Vehicle' class. Within this class, the constructor is utilized to initialize the properties along with their default values.

Subsequently, the instance of the class was created, as illustrated in the output.

Example

<!DOCTYPE html>
<html>
<body>
	<p id = "result"> </p>
	<script>
		// creating Vehicle class
		class Vehicle {
			constructor() {
				this.type = "Car";
				this.brand = "Audi";
				this.cost = 1500000;
			}
		}
		// instantiate myVehicle object
		const myVehicle = new Vehicle();
		// display the properties
		document.getElementById("result").innerHTML = 
      "Vehicle type is : " + myVehicle.type + "<br>"
      +"Vehicle brand is : " + myVehicle.brand + "<br>"
      +"Vehicle cost is : " + myVehicle.cost + "<br>";
	</script>
</body>
</html>

Output:

We can employ the arguments of the constructor method to initialize the class properties in a dynamic manner.

Example: Constructing class objects with arguments

The subsequent example illustrates the creation of the 'Vehicle' class. The constructor method within this class accepts four parameters, which it utilizes to set the class properties with the provided values.

During the instantiation of the 'Vehicle' class, four parameters were provided. This approach allows us to dynamically set the properties of the class.

Example

<!DOCTYPE html>
<html>
<body>
	<p id = "output"> </p>
	<script>
		class Vehicle {
			constructor(brand, model, price, year) {
				this.brand = brand;
				this.model = model;
				this.price = price;
				this.year = year;
			}
		}
		const vehicleObj = new Vehicle("TATA", "AW", 2000000, 2023);
		document.getElementById("output").innerHTML += 
		"Vehicle brand : " + vehicleObj.brand + "<br>"
		+ "Vehicle model : " + vehicleObj.model + "<br>"
		+ "Vehicle price : " + vehicleObj.price + "<br>"
		+ "Vehicle year : " + vehicleObj.year + "<br>"
	</script>
</body>
</html>

Output:

JavaScript Class Methods

Furthermore, you can detail the functions that are included within the class and which can be accessed by the class instance.

Syntax

To declare functions within a class, utilize the following syntax demonstrated below.

Example

class car {
   methodName(parameters) {
		// Method body
	}
}
obj.methodName();

In the previously discussed syntax, the dynamic name of the method is referred to as 'methodName'. When defining a class method, it is not necessary to prepend a keyword such as "function" prior to the method name.

To invoke the class method, it is necessary to use the class instance. In this scenario, 'obj' represents an instance of the class. Additionally, the method is capable of accepting parameters that you can provide.

Example: How to send arguments to class methods is shown in the example below.

The method updateprice has been outlined previously to modify the price of the vehicle. To alter the price, we invoke the updateprice function, passing the new price as a parameter, and utilize it within the body of the method. The following output illustrates both the original and the revised pricing of the vehicle.

Example

<!DOCTYPE html>
<html>
<body>
	<p id = "result"> </p>
	<script>
		class Vehicle {
			constructor(brand, model, price, year) {
				this.brand = brand;
				this.model = model;
				this.price = price;
				this.year = year;
			}

			updateprice(newPrice) {
			this.price = newPrice;
			}
		}
    
		const myVehicle = new Vehicle("Audi", "XZ", 10000000, 2024);
		document.getElementById("result").innerHTML += 
		"The vehicle price is : " + myVehicle.price + "<br>";
    
		myVehicle.updateprice(15000000); // updating price
    
		document.getElementById("result").innerHTML += 
		"After updating the vehicle price is : " + myVehicle.price + "<br>";
	</script>
</body>
</html>

Output:

JavaScript Class Hoisting

In JavaScript, class declarations do not undergo hoisting to the top of the code. As a result, it is imperative to declare a class prior to its utilization.

Example

const vehicleObj = new Vehicle(); // This will generate an error.
class Vehicle {
}

Attempt to run the code provided earlier. Since the vehicle class is referenced prior to its initialization, a reference error will occur.

Class-Based Strict Mode

To avoid unusual errors, the strict mode is utilized. By default, the class code consistently operates in strict mode.

To enhance our understanding, let us examine the following example.

Example

class num {
	constructor() {
		number = 50; // Defining variable without var keyword
	}
}
const numberObj = new num();

Inside the constructor function illustrated in the preceding code, we declare the global variable 'number'. In JavaScript's strict mode, it is mandatory to declare variables using the keywords var, let, or const. As a result, the code presented above will lead to an error.

In summary

  • JavaScript classes serve as object creation blueprints.
  • JavaScript classes are made up of methods and attributes.
  • Data is stored in JavaScript classes via attributes.
  • In JavaScript, methods are used to access the characteristics of classes.
  • The constructor method in JavaScript classes is used to initialize objects.
  • Physical items defined in a JavaScript class declaration are called objects.
  • JavaScript classes declare their internal code using the use-strict prototype.

Input Required

This code uses input(). Please provide values below: