rb_thumb

featured img

Introducing Classes in JavaScript ES6

JavaScript ES6 introduced a new feature called classes, which enables developers to create reusable templates for objects, mirroring the concept of object-oriented programming (OOP) found in languages such as C++ and Java.

In this context, classes serve as blueprints or prototypes that define the structure and behavior of objects, allowing for more organized and maintainable code.

Let’s explore a simple example by creating a Person class:

/ define a class named 'Person'
class Person {
    // class constructor to initialize the 'name' and 'age' properties
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // method to display a message
    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

// create two instances of the Person class
let person1 = new Person("Jack", 30);
let person2 = new Person("Tina", 33);

// call greet() method on two instances 
person1.greet();
person2.greet();

Output*

Hello, my name is Jack and I am 30 years old.
Hello, my name is Tina and I am 33 years old.

In the above example, we have defined a Person class using the class keyword.

Inside Person, we have defined:

Creating a Custom Class in JavaScript

In this article, we will explore how to create a custom class in JavaScript with a constructor function and a method.

The Person Class

The Person class is designed to represent a person’s basic information such as their name and age. To initialize these properties, we can use a class constructor that sets the initial values for each property.

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

The Greet Method

The greet() method is used to display a greeting message using the name and age properties. This method can be defined within the class as follows:

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

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

Creating an Instance of the Person Class

To use our custom Person class, we can create an instance of it by calling the constructor function. For example:

javascript
const person = new Person('John Doe', 30);

Calling the Greet Method

Once we have created an instance of the Person class, we can call the greet() method to display a greeting message:

javascript
person.greet();
// Output: Hello, my name is John Doe and I am 30 years old.

In this example, we have successfully created a custom class in JavaScript with a constructor function that initializes the name and age properties, as well as a method that displays a greeting message using these properties.

Using the new keyword, we have created two objects of the Person class- person1 and person2.

We have then called the greet() method on person1 and person2 using the . operator:

  • person1.greet() – calls greet() on person1
  • person2.greet() – calls greet() on person2

Create Objects Without Classes

Dynamic Object Creation in JavaScript

JavaScript offers the capability to create objects without the need for traditional class definitions. One effective method for achieving this is through object literals.

By utilizing object literals, developers can define and instantiate objects directly within their code, providing a high degree of flexibility and expressiveness.

Let’s look at the example below,

/ create an object 'person' without a formal class definition
let person = {
    name: "Jack",
    age: 30,
    greet: function() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`)
    }
};

// call the greet() method on the person object
person.greet(); 

Output*

Hello, my name is Jack and I am 30 years old.

In the above example, we have created an object named person directly using an object literal.

The person object has:

Defining Properties and Methods in Programming

In programming, objects are often defined by their properties and methods. A property is an attribute or quality of the object, while a method is an action that can be performed on it.

For instance, consider a person object with two key properties: name and age. The name property has the value "Jack", and the age property has the value 30. This means that when we refer to this person object, we know its name is Jack and it’s 30 years old.

In addition to these properties, our person object also has a method called greet(). This method is responsible for displaying a greeting message. When we call the greet() method on our person object, it will output a friendly message such as “Hello, my name is Jack and I’m 30 years old.”

We have called the greet() method on person using the . operator as person.greet().

To learn more about object literals, visit JavaScript Objects.

Features of a JavaScript Class

Mastering Classes in JavaScript: A Step-by-Step Analysis

To fully comprehend the intricacies of classes in JavaScript, let’s delve into the initial code presented at the onset of this tutorial. By dissecting each component, we’ll uncover a profound appreciation for the inner workings of classes.

What to Expect

This article will provide an exhaustive examination of the class structure, examining every aspect to ensure a comprehensive understanding of its functionality.

Let me know if you need any changes or modifications!

/ define a class named 'Person'
class Person {
    // class constructor to initialize the 'name' and 'age' properties
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // method to display a message
    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

// create two objects of the Person class
let person1 = new Person("Jack", 30);
let person2 = new Person("Tina", 33);

// call greet() method on two instances 
person1.greet();
person2.greet();

Output*

Hello, my name is Jack and I am 30 years old.
Hello, my name is Tina and I am 33 years old.

Create a class*

In JavaScript, we create a class using the class keyword. For example,

/ create a class
class Person {
    // body of class
};

Class Constructor*

Class Constructors: The Initialization Gateway

When creating a new object from a class, a crucial process takes place behind the scenes – the execution of the class constructor. A class constructor, also known as an initializer or initialization method, is a special method within a class that automatically runs whenever a new instance of that class is created.

In other words, the class constructor serves as a gateway for initializing objects, allowing developers to set default values, perform necessary calculations, and establish relationships between object attributes. This crucial step ensures that each newly created object starts with a solid foundation, ready to be used in various applications and scenarios.

Constructor of the Person Class

Constructor of the Person Class

The Person class constructor initializes the name and age properties when a new object is created.

  • the person1 object is initialized with "Jack" and 30
  • the person2 object is initialized with "Tina" and 33

A class method is a function inside a class that defines behaviors for the class’s objects.

Method of the Person Class

Method of the Person Class

The Person class boasts a greet() method, which emits a welcoming message upon invocation when instantiated as an object of the class. This method plays a crucial role in facilitating personalized greetings for individuals represented by instances of the Person class.

By admin

Leave a Reply

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