DEV Community

Cover image for JavaScript: Object Creation & Constructor Functions
Megalraja
Megalraja

Posted on

JavaScript: Object Creation & Constructor Functions

While learning JavaScript, I explored how objects can be created and reused.

The simplest way is an object literal:

const laptop = {
    brand: "HP",
    model: "H15",
    price: 45000
};
Enter fullscreen mode Exit fullscreen mode

But when we need multiple objects with the same structure, a constructor function is useful:

function Laptop(brand, model, price) {
    this.brand = brand;
    this.model = model;
    this.price = price;
}
Enter fullscreen mode Exit fullscreen mode
const laptop1 = new Laptop("HP", "H15", 45000);
const laptop2 = new Laptop("MSI", "MSI15", 55000);
Enter fullscreen mode Exit fullscreen mode

Here, new creates a new object, and this refers to that newly created object.

Simple idea:

Constructor → Structure
new → Creates object
this → Sets object properties

A small concept, but an important foundation for understanding JavaScript objects.

Top comments (0)