Constructor Functions & new
Constructor functions are templates for creating multiple objects with the same structure. The 'new' keyword creates a new instance. This is the pre-ES6 way of creating objects — understanding it is essential for understanding prototypes and classes.
Constructor Functions
- Constructor — A regular function used with 'new': function User(name) { this.name = name; }
- new keyword — Creates a new empty object, sets 'this' to it, runs the function, returns the object
- Convention — Constructor names start with uppercase: User, Product, Car
- instanceof — Check if object was created by a constructor: user instanceof User
- Before ES6 — This was the only way to create object blueprints. Now we use classes
Constructor Code
// Constructor function
function User(name, age, role) {
this.name = name;
this.age = age;
this.role = role;
this.greet = function() {
return `Hi, I'm ${this.name} (${this.role})`;
};
}
// Create instances with 'new'
const alice = new User("Alice", 25, "admin");
const bob = new User("Bob", 30, "user");
console.log(alice.greet()); // "Hi, I'm Alice (admin)"
console.log(bob.greet()); // "Hi, I'm Bob (user)"
// instanceof check
console.log(alice instanceof User); // true
console.log(bob instanceof User); // true
// What 'new' does behind the scenes:
// 1. Creates empty object: {}
// 2. Sets 'this' to that object
// 3. Runs constructor code (assigns properties)
// 4. Returns the object
// Without new — 'this' would be wrong!
// const broken = User("Eve", 22, "user"); // ❌ Don't forget new!Tip
Tip
While constructors still work, prefer ES6 classes for new code. Classes have cleaner syntax, built-in inheritance with extends/super, static methods, private fields, and getters/setters. Constructors are important to understand but rarely written directly in modern code.
Classes are syntactic sugar over prototypes.
Common Mistake
Warning
Forgetting the 'new' keyword when calling a constructor. Without new, 'this' points to the global object (or undefined in strict mode), and properties get assigned to the wrong place. The function also returns undefined instead of the new object.
Practice Task
Note
Create a Product constructor: (1) Parameters: name, price, category. (2) Add a method getDiscountedPrice(percent). (3) Create 3 product instances. (4) Verify with instanceof. (5) Try calling without 'new' and observe what happens.
Quick Quiz
Key Takeaways
- Constructor functions are templates for creating multiple objects with the same structure.
- Constructor — A regular function used with 'new': function User(name) { this.name = name; }
- new keyword — Creates a new empty object, sets 'this' to it, runs the function, returns the object
- Convention — Constructor names start with uppercase: User, Product, Car