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
};
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;
}
const laptop1 = new Laptop("HP", "H15", 45000);
const laptop2 = new Laptop("MSI", "MSI15", 55000);
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)