Js Object Constructors in JavaScript
? JavaScript Object Constructors
In JavaScript, object constructors are special functions used to create and initialize objects. They work like blueprints for creating multiple similar objects.
?? Syntax: Object Constructor Function
function Person(name, age) { this.name = name; this.age = age;}???? Create Objects Using new Keyword
let person1 = new Person("Alice", 25);let person2 = new Person("Bob", 30);console.log(person1.name); // "Alice"console.log(person2.age); // 30?? How It Works
A constructor function is defined (capitalized by convention).
The
newkeyword:Creates an empty object:
{}.Sets
thisinside the constructor to that object.Returns the new object.
? Adding Methods to Constructors
function Car(brand, year) { this.brand = brand; this.year = year; this.getAge = function() { return new Date().getFullYear() - this.year; };}let myCar = new Car("Toyota", 2015);console.log(myCar.getAge()); // e.g., 10? Constructor vs Object Literal
| Feature | Constructor | Object Literal |
|---|---|---|
| Reusable structure | ? Good for creating many objects | ? Manual for each object |
| Syntax | Uses function + new | Simple {} syntax |
| Performance | Slightly slower due to new | Slightly faster |
? Pro Tip: Use Prototypes for Shared Methods
function Dog(name) { this.name = name;}Dog.prototype.bark = function() { return this.name + " says woof!";};let dog = new Dog("Buddy");console.log(dog.bark()); // "Buddy says woof!"? Summary
Object constructors are custom functions to create objects.
Use
thisto set properties and methods.Always use the
newkeyword to invoke a constructor.For efficiency, define methods on the prototype.
Would you like to see how this transitions into ES6 class syntax?