Object Constructors
Before classes, a constructor function + new was the way to make many objects with shared methods. Modern code uses class, but understanding constructors explains how classes work under the hood.
Constructor function
JS
// Convention: capitalised name
function User(name, role = "member") {
this.name = name;
this.role = role;
}
// Methods go on the prototype — shared by all instances
User.prototype.greet = function () {
return `Hi, ${this.name}!`;
};
const u = new User("Ada", "admin");
u.greet(); // "Hi, Ada!"
u instanceof User; // true
What new actually does
- Creates a fresh empty object.
- Sets its prototype to
Fn.prototype. - Calls
Fnwiththisbound to the new object. - Returns the object (unless the function returned another object).
Class — same machinery, nicer syntax
JS
class User {
constructor(name, role = "member") {
this.name = name;
this.role = role;
}
greet() { return `Hi, ${this.name}!`; }
}
Functionally identical: typeof User === "function", new User works, and methods land on User.prototype.
Built-in constructors you've used
| Constructor | What you get |
|---|---|
new Date() | A Date instance |
new Map() / new Set() | A Map / Set |
new Error("msg") | An Error |
new Promise(executor) | A Promise |
new URL("https://…") | A parsed URL object |
Tip: If you forget the
new on a constructor function, this becomes undefined (strict) or window (sloppy) — silent bugs. Modern class calls throw a TypeError, which is much friendlier.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Object Constructors!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Invoke a constructor function properly.
const u =
User('Ada');
Three letters.
Discussion
Loading…