𝗢𝗯𝗷𝗲𝗰𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
JavaScript constructors help you build objects efficiently. You can use them to create many objects with the same structure.
Constructor Functions
A constructor is a function for initializing objects. Use the new keyword to call it. If you forget the new keyword, the function will not work as intended.
Always start constructor names with a capital letter. This helps you tell them apart from regular functions.
Example:
- Person(name, age)
Object.create()
You can use Object.create() to make a new object using an existing object as a prototype. This method sets up inheritance between objects.
Default Values
You can set default values in your constructor. This ensures your objects always have valid data. If you do not provide a value, the constructor uses the default.
Example: function Person(name = "Unknown", age = 0) { this.name = name; this.age = age; }
Prototypes and Memory
Adding methods to a prototype saves memory. Instead of every object having its own copy of a function, they all share one version from the prototype.
Example: Person.prototype.greet = function() { console.log("Hello " + this.name); };
Inheritance
Classes allow one class to inherit from another. Use the super() keyword to call the parent constructor. This lets child classes use properties and methods from parent classes.
Why use constructors?
- Reusability: Create many objects from one template.
- Organization: Keep object setup logic in one place.
- Initialization: Set specific values immediately during creation.
- Inheritance: Build complex objects from simpler ones.
- Maintenance: Makes your code easier to read and manage.
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