iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

  1. Creates a fresh empty object.
  2. Sets its prototype to Fn.prototype.
  3. Calls Fn with this bound to the new object.
  4. 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

ConstructorWhat 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');

Test yourself

Q1. Convention: a constructor function name is…
Q2. Calling a class without `new` results in…
Q3. Methods defined inside a class go on…

Discussion

Loading…