JavaScript Notes
Understand JavaScript constructor functions with the new keyword, prototype methods, object creation, comparison with ES6 classes, and interview-ready Q&A.
Before ES6 classes arrived, constructor functions were the primary way to create multiple objects with the same shape. A constructor function is simply a regular function that is called with the new keyword. JavaScript then automatically creates a new object, sets this to that object, and returns it.
Constructor functions are still widely used, and understanding them is essential for understanding how JavaScript classes work under the hood.
📊 What new Does — Step by Step
💻 Example 1 — Basic Constructor Function
function Person(name, age) {
// 'this' refers to the newly created object
this.name = name;
this.age = age;
}
// Add shared methods on the prototype — not inside the constructor
Person.prototype.greet = function() {
return `Hi, I am ${this.name}!`;
};
Person.prototype.isAdult = function() {
return this.age >= 18;
};
const riya = new Person("Riya", 22);
const aman = new Person("Aman", 16);
console.log(riya.greet());
console.log(aman.greet());
console.log(riya.isAdult());
console.log(aman.isAdult());
console.log(riya.constructor === Person);Hi, I am Riya! Hi, I am Aman! true false true
💻 Example 2 — Why Methods Go on Prototype (Not Inside Constructor)
// ❌ BAD: method inside constructor — new function created for EVERY instance
function BadUser(name) {
this.name = name;
this.greet = function() { return `Hello, ${this.name}`; }; // NEW fn each time
}
const u1 = new BadUser("Riya");
const u2 = new BadUser("Aman");
console.log(u1.greet === u2.greet); // false — different function objects!
// ✅ GOOD: method on prototype — shared by ALL instances
function GoodUser(name) {
this.name = name;
}
GoodUser.prototype.greet = function() { return `Hello, ${this.name}`; };
const g1 = new GoodUser("Riya");
const g2 = new GoodUser("Aman");
console.log(g1.greet === g2.greet); // true — same shared functionfalse true
💻 Example 3 — Inheritance with Constructor Functions
// Parent constructor
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return `${this.name} makes a sound.`;
};
// Child constructor
function Dog(name, breed) {
Animal.call(this, name); // inherit properties from Animal
this.breed = breed;
}
// Set up prototype chain
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // fix constructor reference
Dog.prototype.bark = function() {
return `${this.name} barks! 🐕`;
};
const dog = new Dog("Bruno", "Labrador");
console.log(dog.speak()); // inherited from Animal
console.log(dog.bark()); // own method
console.log(dog instanceof Dog);
console.log(dog instanceof Animal);Bruno makes a sound. Bruno barks! 🐕 true true
💻 Example 4 — Constructor Function vs ES6 Class (Side by Side)
Riya: Grade A Aman: Grade B function function
📋 Constructor Function vs Factory Function vs Class
| Feature | Constructor Function | Factory Function | ES6 Class |
|---|---|---|---|
Called with new | ✅ Required | ❌ No new needed | ✅ Required |
this binding | Auto-bound by new | Manual (closure/return) | Auto-bound by new |
| Prototype sharing | Manual .prototype | No prototype by default | Automatic |
| Private data | Closures (workaround) | Natural via closure | #privateField |
| Inheritance | Object.create() | Mixins/composition | extends + super |
| Readability | Moderate | Easy for simple cases | Best for OOP |
⚠️ Common Mistakes
❌ Mistake 1 — Calling Constructor Without new
function Car(brand) {
this.brand = brand;
}
const c = Car("Toyota"); // ← missing 'new'
console.log(c); // undefined — Car returned nothing
console.log(brand); // "Toyota" — leaked onto global scope! 😱undefined Toyota
Fix: Always usenew Car("Toyota"). Or add a guard:if (!(this instanceof Car)) return new Car(brand);
❌ Mistake 2 — Arrow Functions Cannot Be Constructors
TypeError: Person is not a constructor
❌ Mistake 3 — Forgetting to Fix constructor After Prototype Reset
function Animal(name) { this.name = name; }
function Dog(name) { Animal.call(this, name); }
Dog.prototype = Object.create(Animal.prototype);
// ← Missing: Dog.prototype.constructor = Dog;
const d = new Dog("Bruno");
console.log(d.constructor === Dog); // false — broken!
console.log(d.constructor === Animal); // true — wrong!false true
🎯 Key Takeaways
- Constructor functions are regular functions called with
new— nothing special about them except the convention of PascalCase naming newcreates an empty object, sets__proto__, runs the body withthis= new object, returns that object- Put methods on
.prototype— not inside the constructor — so they are shared by all instances - Use
Object.create(Parent.prototype)+Parent.call(this, ...)for constructor-function inheritance - ES6
classis cleaner syntax for the same prototype mechanism — always prefer classes for new code - Arrow functions cannot be used as constructors
- Understanding constructor functions helps you read legacy code and understand how
classworks internally
❓ Interview Questions
Q1. What is a constructor function in JavaScript? > A constructor function is a regular function called with new. The new keyword creates an empty object, sets its prototype to FunctionName.prototype, runs the function with this pointing to that object, and returns it automatically.
Q2. What does the new keyword do step by step? > 1. Creates a new empty object {}. 2. Sets __proto__ to Constructor.prototype. 3. Calls the constructor function with this = new object. 4. Returns the new object (unless the constructor explicitly returns a different object).
Q3. Why should methods be placed on the prototype and not inside the constructor? > Methods defined inside the constructor are re-created as separate function objects for every instance, wasting memory. Methods on the prototype are created once and shared by all instances via the prototype chain.
Q4. What is the difference between a constructor function and an ES6 class? > ES6 class is syntactic sugar over constructor functions. Both use prototypes under the hood. Classes add stricter rules: must use new, not hoisted, always strict mode, and support private fields (#). The output of typeof MyClass is "function".
Q5. How do you implement inheritance with constructor functions? > Use ParentConstructor.call(this, args) to copy parent properties, and Child.prototype = Object.create(Parent.prototype) to set up the prototype chain. Then fix Child.prototype.constructor = Child.
Q6. What happens if you call a constructor function without new? > this inside the function refers to the global object (or undefined in strict mode). Properties get assigned to the global scope (a dangerous bug). The function returns undefined since there is no implicit return.
Q7. Can arrow functions be used as constructors? > No. Arrow functions do not have their own this, arguments, or prototype. Calling new ArrowFn() throws TypeError: ArrowFn is not a constructor.
Q8. What is prototype.constructor and why does it matter? > Every function's prototype object has a constructor property pointing back to the function itself. When you set Child.prototype = Object.create(Parent.prototype), you lose this link and must restore it: Child.prototype.constructor = Child.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Constructor Functions – new Keyword, Prototype & OOP Patterns.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, oop, constructor, function
Related JavaScript Master Course Topics