𝗢𝗯𝗷𝗲𝗰𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁

You often need to create many objects of the same type. JavaScript gives you several ways to do this.

Constructor Functions

A constructor is a special function to build and set up objects. Use the new keyword to call it. Always start the function name with a capital letter. This helps you tell it apart from regular functions.

If you forget the new keyword, the function works like a standard function and fails to create a proper object.

Default Values

You can set default values in your constructor. This ensures your objects always have valid data even if you miss an argument.

Example: function Person(name = "Unknown", age = 0) { this.name = name; this.age = age; }

Prototypes and Memory

Adding methods to a prototype is smarter than adding them directly to a constructor. When you use the prototype, all instances share one single method. This saves memory because the computer does not recreate the method for every new object.

Object.create()

This method creates a new object using an existing object as its prototype. It establishes inheritance without needing a constructor. The new object can access properties from the original object.

Class Inheritance

Modern JavaScript uses classes to handle inheritance. You can create a child class that extends a parent class. Use the super() keyword to pass data from the child to the parent. This allows the child to use properties from the parent while adding its own unique features.

Why use constructors?

Source: https://www.geeksforgeeks.org/javascript/js-constructor-method/ Source: https://www.w3schools.com/js/js_object_constructors.asp Full post: https://dev.to/kamalesh_ar_6252544786997/object-constructors-in-javascript-2e96

Optional learning community: https://t.me/GyaanSetuAi