JavaScript Class

About JavaScript Class

In JavaScript, a class is a user-defined blueprint (template) for creating object with specific properties and methods.

Class provides a means of bundling (grouping) data and functionality together. In other words, data (properties) and methods (functions) are defined in the class which can be used when objects are created.

Classes make object-oriented code easier to read and understand.

Defining a Class With Basic Syntax

A class can be defined using the class keyword followed by the class name (usually capitalized).

Properties and methods are defined inside the class.

Example of Defining Class
Explanation of The Code
  • class Person: A class is defined using class keyword. Person is the name of the class.
  • constructor(name, age): The constructor method initializes the properties of the Person class. It takes two parameters: name and age. These parameters will be assigned to the name and age properties of the object when it will be created.
  • this.name = name;: This sets the name (this.name) property of class with name parameter.
  • this.age = age;: This sets the age (this.age) property of class with age parameter.
  • introduce() {console.log(`Hello, I am ${this.name}. I am ${this.age} years old.`);}: This is a method (introduce()) of the Person class.

Creating an Object of a Class

To create an object of a class in JavaScript, the new keyword is used along with the class name (e.g. new Person()).

Any required arguments need to be passed to the constructor of the class.

Example of Creating an Object of a Class
Output of the above example
Hello, I am John. I am 25 years old.
Hello, I am Jen. I am 18 years old.
                                
Explanation of The Code
  • const personObj = new Person("John", 25);: This line of code creates an object (personObj) of the Person class by passing two arguments: "John" and 25. You can create as many objects of a class as you require.
  • personObj.introduce();: This line calls the introduce() method of the 'Person' class through the 'personObj' object.

Components of Class


The key components of a class are constructor, properties, members, methods and getters/getters.

1. Constructor

The constructor is a special method used for initializing objects created from the class.

It sets up the initial values for the object's properties.

It is automatically called when a new instance of the class is created.

Example of Class Constructor
Output of the above example
Hello, I am John. I am 25 years old.
                                
Explanation of the code
  • constructor(name, age): The constructor method initializes the properties of the Person class. It takes two parameters: name and age. These parameters will be assigned to the name and age properties of the object when it will be created.
  • this.name = name;: Here, the class property this.name is initialized with the 'name' argument.
  • const personObj = new Person("John", 25);: This line of code creates an object (personObj) of the Person class. Two arguments: "John" and 25 are passed as arguments to set up the initial values for the object's properties 'name' and 'age'. Two arguments are passed as the constructor takes two arguments.

2. Properties

Properties are variables that belong to an object created from a class.

They are usually defined and initialized inside the constructor using the this keyword.

Example of Class Object Properties
Output of the above example
Jenifer
                 
Explanation of the code
  • this.name = name; this.age = age;: Here, this.name and this.name are class object properties. They are initialized when an object of the Person class is created with arguments (name, age).
  • const personObj = new Person("Jenifer", 17);: This line of code creates an object (personObj) of the Person class. Two arguments: "Jenifer" and 17 are passed as arguments to set up the initial values for the object's properties 'name' and 'age'.
  • var personName = personObj.name;: Here, personObj.name is used to access the 'name' property value of the 'personObj' object.

3. Methods

Methods are functions defined inside a class.

Methods represent the behavior or actions of the objects created from the class.

Static methods can be called directly using class name, while instance methods require an instance of the class to be called.

Example of Class Methods
Output of the above example
Message from static method.
Hello, Jenifer
                 
Explanation of the code
  • static message(){...}: This defines static method using the static keyword before the message() method. This method can be called directly using the Person class name.
  • greet(){...}: This defines instance method (as the static keyword is not used before the greet() method). This instance method requires an instance of the class to be called.
  • let message = Person.message();: The message() method is called using the Person class name.
  • personObj.greet();: The greet()) method is called using the instance (personObj object) of Person class. An instance (object) of the Person class is created with this code const personObj = new Person("Jenifer").

4. Fields

In JavaScript class, fields are properties that are defined directly inside the body of a class, but outside the constructor.

Public fields can be accessed or modified directly on the instances of the class.

Private fields are accessible only within the class where they are defined. They are prefixed with a # symbol.

Static fields can be accessed using class name (without creating an instance of a class ).

Example of Class Fields
Output of the above example
300
                 
Explanation of the code
  • #previousBalance;: This declares a private field using # symbol at the start of the name. This field cannot be accessed from outside the class.
  • newBalance;: This declares a public field which can be accessed from outside the class using instance of the class.
  • personObj.newBalance;: This accesses the public field 'newBalance' using instance of the class.
Example of Class Static Field
Explanation of the code
  • static piValue = 3.14;: This declares a static field 'piValue' using the static keyword.
  • static goldenRatio = 1.618;: This declares a static field 'goldenRatio' using the static keyword.
  • Math.piValue: To access the value of static field 'piValue', the class name 'Math' is used (no object is created).
  • Math.goldenRatio: To access the value of static field 'goldenRatio', the class name 'Math' is used (no object is created).

5. Getters and Setters

Getters methods retrieve or compute the value of a property. The get keyword is used before method name.

Setters methods set or update the value of a property. The set keyword is used before method name.

Example of Class Getters and Setters
Output of the above example
John
Jane
                 
Explanation of the code
  • get name(){return this._name;}: This declares a get method and returns _name value.
  • set name(newName){this._name = newName;}: This declares a set method and sets new value to the name property.
  • person.name = "Jane";: This sets new value to the name property using setter.

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript editor. Create more classes and their objects in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Compiler
JavaScript Code Output