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

Object Prototypes

Every JavaScript object has a hidden link to another object called its prototype. Property lookups walk this chain — that's how inheritance works.

The chain

dog { name: "Rex" } Dog.prototype { bark() } Object.prototype { toString, … }
Fig 1. Looking up dog.toString walks the chain until it finds the method.

Inspecting and setting

JS
const animal = { eat() { console.log("om nom"); } };
const dog    = Object.create(animal);   // dog's prototype IS animal
dog.bark = function () { console.log("woof"); };

dog.bark();                              // "woof"
dog.eat();                               // "om nom" — inherited

Object.getPrototypeOf(dog) === animal;   // true
Object.setPrototypeOf(dog, otherProto);  // works, but expensive — avoid at hot paths

Classes are sugar over prototypes

JS
class User {
  constructor(name) { this.name = name; }
  greet() { return `Hi, ${this.name}!`; }
}

const u = new User("Ada");
u.greet();                          // "Hi, Ada!"
Object.getPrototypeOf(u) === User.prototype;   // true
typeof User.prototype.greet;        // "function"  ← that's where the method lives
Note: Methods on a class go on Class.prototype — every instance shares the same function. Class fields (name = …) get copied to each instance.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Object Prototypes!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Get an object's prototype using the standard helper.

const proto = Object. (obj);

Test yourself

Q1. Class methods live on…
Q2. Get an object's prototype with…
Q3. Create an object with a chosen prototype using…

Discussion

Loading…