DEV Community

Cover image for Modern JavaScript: Understanding ES6 Classes
Karthick Karthick
Karthick Karthick

Posted on

Modern JavaScript: Understanding ES6 Classes

What is Constructor Functions:

You often need to create multiple objects with the same structure. Instead of writing objects repeatedly, JavaScript provides Constructor Functions to make object creation easier and reusable.

Explanation

  • function Person() → Constructor function (capital letter by convention)

  • this.name → property of the object

  • this.age → another property

  • At this stage no object is created yet.

  • The function only defines how objects should be built

What Happens When new is Used ?

Step 1 — Create Empty Object

Step 2 — this Points to the Object

Step 3 — Add Properties

Step 4 — Return the Object

Then

Role of this in Constructor Functions:
In a constructor function, the keyword this refers to the new object that is being created.

When you create an object using the new keyword, JavaScript automatically creates an empty object and sets this to that object inside the constructor.

Modern Alternative — ES6 Classes:
ES6 Classes are the modern way to create objects in JavaScript, introduced in ECMAScript 2015 (ES6).

Before ES6, developers used constructor functions to create objects.
Now JavaScript provides classes, which make the code cleaner and easier to read.

Simple to Understand:

Top comments (0)