Thuta Learning
JavaScript
IntermediateProgrammingBeginner

Prototypes

JavaScriptLesson 1825 min

What you'll walk away with

  • Explain, step by step, how reading a property walks the prototype chain
  • Put methods on Constructor.prototype so every instance shares them
  • Use Object.hasOwn and Object.getPrototypeOf to find out where a property comes from
  • Avoid shadowing surprises, shared arrays on prototypes and prototype pollution

Explain it simply

Explain it simply

Imagine looking for salt at home. You check your own kitchen first; if it is not there you ask your neighbour, and if they have none you go to the corner shop. Only when the shop has none either do you give up and say "there is no salt".

JavaScript objects work the same way. Every object is linked to a "neighbour" object called its prototype, and a property it does not have is looked up on the prototype, then on the prototype's prototype, and so on. That line of links is the prototype chain, and all of JavaScript's inheritance is built on it.

Problem → Why → Solution

The problem: a key you never added is already there

A word counter is written with a plain {} object. It works for "apple", but when a user types the word "constructor", the count turns into a strange string instead of a number. Nobody ever put a constructor key into counts.

word-count.js
const counts = {};
for (const word of ["apple", "constructor", "apple"]) {
  counts[word] = (counts[word] || 0) + 1;
}

console.log(counts.apple);       // 2
console.log(counts.constructor); // "function Object() { [native code] }1"

Why does this happen?

{} is linked to Object.prototype, so reading counts["constructor"] finds nothing on counts, climbs to the prototype and finds the Object function. A function is truthy, so || 0 never kicks in, and function + 1 becomes string concatenation. Understanding the prototype chain is what explains the bug, and the fixes are checking with Object.hasOwn, using Object.create(null), or using a Map.

Core concept: how lookup walks the prototype chain

Every object has a hidden link called [[Prototype]] that points to another object or to null. Reading obj.key makes JavaScript (1) look on obj itself, (2) if missing, look on its prototype, (3) keep climbing until the chain ends at null, and (4) return undefined if nothing matched. Read the link with Object.getPrototypeOf(obj); the __proto__ accessor is a legacy feature to avoid in new code.

Every function has an ordinary property named prototype. new Vehicle("car") sets the new object's [[Prototype]] to Vehicle.prototype. So when you write Vehicle.prototype.describe once, every Vehicle instance shares that single function, which saves memory. Class methods live on exactly this kind of prototype object; class syntax is just a tidier way of writing it. Lookup is live, so a method added to the prototype after instances exist is visible to them immediately.

Reading and writing behave differently. A read climbs the chain, but an assignment like bike.wheels = 2 does not touch the prototype; it creates a new own property on bike. That own property hides the prototype's wheels, which is called shadowing. To ask whether a property sits on the object itself, use Object.hasOwn(obj, key); key in obj checks the whole chain and is also true for inherited properties.

A plain object has a very short chain: obj, then Object.prototype, then null. Every object literal can call toString() and hasOwnProperty() because those methods live on Object.prototype. An array's chain is arr, then Array.prototype, then Object.prototype, then null. However long the chain, a read searches from the bottom up, so the property closest to the object always wins.

Mental model: reads climb, writes stay home
  1. Look on the object itself first
  2. Missing? Climb to [[Prototype]]
  3. Reached null? Result is undefined
  4. Writes land on the object itself

Reads search up the chain, but plain writes never modify the prototype (unless a setter is involved).

General pattern

javascript
function Constructor(arg) {
  this.ownProp = arg;                  // per instance
}
Constructor.prototype.sharedMethod = function () {
  return this.ownProp;                 // shared by all instances
};

const instance = new Constructor(value);
Object.getPrototypeOf(instance) === Constructor.prototype; // true
Object.hasOwn(instance, "ownProp");      // true
Object.hasOwn(instance, "sharedMethod"); // false

Per-instance data goes on this inside the constructor, and shared methods go on Constructor.prototype. Object.getPrototypeOf checks the link, and Object.hasOwn tells you whether a property is the instance's own.

Example: the Vehicle prototype

The Vehicle constructor puts type on each instance and shares describe() and wheels on the prototype. bike shadows wheels, and the last three lines check where each property lives with Object.hasOwn(), the modern replacement for calling car.hasOwnProperty() directly.

vehicle.js
// Constructor function
function Vehicle(type) {
  this.type = type;
}

// Shared by every Vehicle through the prototype
Vehicle.prototype.describe = function () {
  return `This is a ${this.type}`;
};
Vehicle.prototype.wheels = 4;

const car = new Vehicle("car");
const bike = new Vehicle("bike");
bike.wheels = 2; // own property on bike shadows the prototype's

console.log(car.describe());
console.log(`Car wheels: ${car.wheels}`);
console.log(bike.describe());
console.log(`Bike wheels: ${bike.wheels}`);

// Own property or inherited?
console.log(Object.hasOwn(car, "type"));     // true
console.log(Object.hasOwn(car, "describe")); // false (lives on the prototype)
console.log(Object.getPrototypeOf(car) === Vehicle.prototype); // true

Code breakdown

  1. Lines 7-9Vehicle.prototype.describe = function () {

    describe is created once on the prototype, so car and bike share a single function. It must be a function expression, not an arrow, so that this is the object it is called on.

  2. Line 10Vehicle.prototype.wheels = 4;

    Plain values can live on the prototype too, not just methods. Any instance without its own wheels sees 4 as a default.

  3. Line 14bike.wheels = 2; // own property on bike shadows the prototype's

    The assignment does not change Vehicle.prototype.wheels; it creates a new own property on bike. That is why car still sees 4 while bike sees 2.

  4. Line 16console.log(car.describe());

    car has no describe of its own, so lookup climbs to Vehicle.prototype and finds it. During the call, this is car, giving "This is a car".

  5. Lines 22-23console.log(Object.hasOwn(car, "describe")); // false (lives on the prototype)

    type was put directly on car by the constructor, so it is an own property; describe is inherited, so the check is false. car.describe works, yet it is not car's own property.

You should see
This is a car
Car wheels: 4
This is a bike
Bike wheels: 2
true
false
true

Object.create and a class's prototype

Object.create(proto) builds an object with a prototype you choose directly, no constructor needed. Object.create(null) gives a "dictionary" object with no prototype at all, which makes the constructor bug from the problem section impossible. To see where a class keeps its methods, inspect Object.getOwnPropertyNames(ClassName.prototype).

object-create.js
const animal = {
  describe() { return `${this.name} says ${this.sound}`; },
};
const cat = Object.create(animal);
cat.name = "Whiskers";
cat.sound = "meow";
console.log(cat.describe());                     // Whiskers says meow
console.log(Object.getPrototypeOf(cat) === animal); // true

const dict = Object.create(null);
console.log(dict.constructor);                   // undefined

class Point { norm() { return 0; } }
console.log(Object.getOwnPropertyNames(Point.prototype)); // [ 'constructor', 'norm' ]

In real projects

Where this shows up in real projects

Open any object in the browser DevTools and you will see a [[Prototype]] entry. Debugging questions like "where does this method come from?" or "why did this value change?" are answered by expanding that chain one level at a time. It is also where you see that array methods such as map and filter live on Array.prototype and string methods on String.prototype.

On the security side, prototype pollution is a real class of vulnerability. If user-supplied JSON contains a "__proto__" key and a deep-merge function copies it without checking, a property like isAdmin: true lands on Object.prototype and every object in the app can see it. Several widely used merge utilities have shipped this bug. Defend by rejecting __proto__, constructor and prototype keys, and by using a Map or Object.create(null) for user-keyed data.

Common mistakes

Common mistakes

1. Sharing an array or object on the prototype

With Vehicle.prototype.passengers = [], calling car.passengers.push("Su") is not an assignment, so no own property is created; it mutates the one array on the prototype. "Su" now shows up in bike.passengers too. Create per-instance arrays and objects in the constructor: this.passengers = [].

2. Writing a prototype method as an arrow function

Vehicle.prototype.describe = () => `This is a ${this.type}` gives the arrow function no this of its own, so even car.describe() does not see car. In an ES module this is undefined and the call throws a TypeError; in a classic script it quietly returns "This is a undefined". Write prototype methods as function expressions or class methods.

3. Modifying built-in prototypes

Adding Array.prototype.last = function () {...} is tempting, but it collides when another library or a future JavaScript version adds a method with the same name. An old library's Array.prototype.flatten is the reason the standard method ended up being called flat. Use a helper function such as last(array) instead.

Best practices

Best practices

  • Write class syntax in new code instead of hand-written prototypes; use your prototype knowledge for debugging.
  • Read prototypes with Object.getPrototypeOf, check own properties with Object.hasOwn, and avoid __proto__.
  • When user-provided strings become keys, choose a Map or Object.create(null) over a plain {}.
  • Keep only methods and immutable defaults on a prototype; create mutable arrays and objects inside the constructor.

Mini challenge

Mini challenge: find where a property lives

Write a whereIs(obj, key) function that climbs the prototype chain itself and reports at which level a property lives.

  • Return "<key>: own property" when the object itself has it
  • Return "<key>: found on prototype #<level>" when a prototype has it (the first prototype is #1)
  • Return "<key>: not found" when the chain runs out
  • Use only Object.hasOwn and Object.getPrototypeOf, not the in operator
where-is.js
function whereIs(obj, key) {
  // TODO: start at obj with level 0
  // TODO: loop until the current object is null
  //   - if the current object owns key, report "own property" or the level
  //   - otherwise move to its prototype and add 1 to the level
  // TODO: report "not found"
}

// TODO: a Shape constructor that stores name on the instance
// TODO: a describe() method on Shape.prototype

// TODO: create a square and check "name", "describe", "toString", "area"

Expected: The console prints four lines: name: own property describe: found on prototype #1 toString: found on prototype #2 area: not found

Show hint

Inside a while (current !== null) loop, step upward with current = Object.getPrototypeOf(current). toString lives on Object.prototype, so it should be found two levels above square.

Show solution
where-is.js
function whereIs(obj, key) {
  let current = obj;
  let level = 0;
  while (current !== null) {
    if (Object.hasOwn(current, key)) {
      if (level === 0) return `${key}: own property`;
      return `${key}: found on prototype #${level}`;
    }
    current = Object.getPrototypeOf(current);
    level++;
  }
  return `${key}: not found`;
}

function Shape(name) {
  this.name = name;
}
Shape.prototype.describe = function () {
  return `A ${this.name}`;
};

const square = new Shape("square");
for (const key of ["name", "describe", "toString", "area"]) {
  console.log(whereIs(square, key));
}

Quick quiz 1 / 3

After the example, what does delete bike.wheels; console.log(bike.wheels); print?

Quick quiz 2 / 3

If Vehicle.prototype.honk = function () { return "Beep"; }; is added after car was created, what does car.honk() do?

Quick quiz 3 / 3

A user-supplied JSON object might contain a key named "hasOwnProperty". Which own-property check is safest?

What to remember

  • Every object has a [[Prototype]] link, and reads search along the chain until null.
  • new Fn() links the instance to Fn.prototype, so methods on the prototype are shared by every instance.
  • Assignment creates an own property that shadows the prototype's value.
  • Use Object.hasOwn and Object.getPrototypeOf, never patch built-in prototypes, and prefer a Map for user-keyed data.

MDN — Using Classes — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Prototypes | Thuta Learning