𝗢𝗯𝗷𝗲𝗰𝘁 𝗖𝗼𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
You need to create many objects of the same type. JavaScript offers several ways to do this efficiently.
Constructor Functions
A constructor is a function used to set up new objects. Use these rules to avoid errors:
- Capitalize the first letter of the function name. This helps you identify it as a constructor.
- Use the new keyword. If you forget this, the function runs like a normal function and fails to create the object.
Default Values
You can set default values in your constructor. This ensures your objects stay valid even if you skip some details.
Example: function Person(name = "Unknown", age = 0) { this.name = name; this.age = age; }
If you call new Person(), the name becomes "Unknown" and the age becomes 0.
Object.create()
You can use Object.create() to make a new object based on an existing one. This uses prototype-based inheritance. Instead of copying data, the new object links to the original prototype.
Memory Optimization
Do not put methods inside the constructor itself. If you do, every new object gets its own copy of that method. This wastes memory.
Instead, add methods to the prototype. This way, all objects share one single version of the method.
Example: Person.prototype.greet = function() { console.log("Hello " + this.name); };
Inheritance
Classes allow one class to inherit from another. Use the super() keyword in a child class to call the parent constructor. This lets the child access properties from the parent.
Benefits of using constructors:
- Reusable code: Create many objects with one pattern.
- Clean logic: Keep object setup in one place.
- Easy initialization: Set specific values during creation.
- Inheritance: Build complex objects from simpler ones.
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