
Understanding Constructor Functions in JavaScript
In JavaScript, a constructor function is used to create multiple objects with similar properties and methods. Instead of creating objects manually again and again, we use a constructor to generate them easily. What is an Object? An object stores data in key–value pairs. Example: let person = { name : " Harini " , age : 22 }; Here: name and age are keys "Harini" and 23 are values If we want to create many similar objects, writing this structure repeatedly is not efficient. That’s why we use constructor functions. What is a Constructor Function? A constructor function is a normal function used to create objects. By convention, constructor function names should start with a capital letter. Example: function User () { this . name = " Harini " ; } Here: this refers to the newly created object. this.name assigns a property to that object. Creating an Object Using new To create an object from a constructor, we use the new keyword. let user1 = new User (); console . log ( user1 ); What happens
Continue reading on Dev.to
Opens in a new tab



