When called with **new**, a constructor function: (1) creates a new empty object, (2) sets its `__proto__` to `Constructor.prototype`, (3) runs the function body with `this` = new object, (4) returns the object. Methods defined on `Constructor.prototype` are shared across all instances (memory efficient).
1Understanding Constructor Functions
When called with new, a constructor function: (1) creates a new empty object, (2) sets its __proto__ to Constructor.prototype, (3) runs the function body with this = new object, (4) returns the object. Methods defined on Constructor.prototype are shared across all instances (memory efficient).
Modern JavaScript prefers class syntax over constructor functions — it's syntactic sugar over the same prototype mechanism but much more readable.
function Animal(name, sound) {
this.name = name;
this.sound = sound;
}
// Shared method on prototype
Animal.prototype.speak = function() {
return `${this.name} says ${this.sound}`;
};
const dog = new Animal('Dog', 'woof');
const cat = new Animal('Cat', 'meow');
console.log(dog.speak()); // Dog says woof
console.log(cat.speak()); // Cat says meow2Practical Example
Here is a real-world application of Constructor Functions showing how it is used in production JavaScript code.
// What 'new' actually does
function fakeNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype);
const result = Constructor.apply(obj, args);
return result instanceof Object ? result : obj;
}
const p = fakeNew(Animal, 'Parrot', 'squawk');
console.log(p.speak());3Best Practices
Follow these guidelines when working with Constructor Functions:
1. Capitalize constructor function names
2. Add shared methods to Constructor.prototype
3. Prefer class syntax in modern code
Tip: Modern JavaScript prefers class syntax over constructor functions — it's syntactic sugar over the same prototype mechanism but much more readable.
function Animal(name, sound) {
this.name = name;
this.sound = sound;
}
// Shared method on prototype
Animal.prototype.speak = function() {
return `${this.name} says ${this.sound}`;
};
const dog = new Animal('Dog', 'woof');
const cat = new Animal('Cat', 'meow');
console.log(dog.speak()); // Dog says woof
console.log(cat.speak()); // Cat says meow