Prototype Chain & OOP

Published by Brayan K

The prototype chain is the series of linked objects JavaScript walks up when looking for a property or method, inheriting from each object's prototype until it finds the property or reaches the end of the chain.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Find the owner of a property, not just its visible value

Prototypes and Classes owns construction, class methods and the basic instance-to-prototype link. This lesson follows a property through multiple objects, distinguishes data from accessors, and checks what a copied method actually retains. The examples use ordinary objects; proxy traps and host objects need additional care.

const base = { theme: "light", enabled: true };
const middle = Object.create(base);
middle.theme = "dark";
const settings = Object.create(middle);
settings.theme = undefined; // A property exists even though its value is undefined.
console.log(settings.theme, Object.hasOwn(settings, "theme"));
console.log("enabled" in settings, Object.hasOwn(settings, "enabled"));
delete settings.theme; // Reveal the nearest inherited definition.
console.log(settings.theme);
delete middle.theme;
console.log(settings.theme);
console.log(Object.getPrototypeOf(settings) === middle);

// ✅ Expected output:
// undefined true
// true false
// dark
// light
// true

Lookup stops at the first matching property. It does not continue searching because the value is undefined, null, false or zero. The in operator includes inherited properties; Object.hasOwn asks only about the object itself. Use the question that matches the data contract, especially for configuration or input records.

The receiver stays the original object during inherited access

const base = {
  get label() { return this.name.toUpperCase(); }
};
const first = Object.create(base);
first.name = "mina";
const second = Object.create(base);
second.name = "leo";
console.log(first.label, second.label);
console.log(Object.hasOwn(first, "label"));
console.log(Object.getOwnPropertyDescriptor(base, "label").get ===
  Object.getOwnPropertyDescriptor(Object.getPrototypeOf(second), "label").get);

// ✅ Expected output:
// MINA LEO
// false
// true

The getter is found on base, but this is the object used for the access. Getters, Setters & Property Descriptors owns accessor syntax and descriptor flags; here the important distinction is property owner versus receiver.

const base = {
  set score(value) { this.savedScore = value; },
  get score() { return this.savedScore; }
};
const item = Object.create(base);
item.score = 7;
console.log(item.score, Object.hasOwn(item, "savedScore"));
console.log(Object.hasOwn(item, "score"), Object.hasOwn(base, "savedScore"));

// ✅ Expected output:
// 7 true
// false false

Assignment is not always “create a property with that name on the child.” The inherited setter runs and chooses what to do. An inherited non-writable data property can prevent assignment instead. Inspect its descriptor before assuming a write will shadow it.

const base = {};
Object.defineProperty(base, "id", { value: 7, writable: false });
const item = Object.create(base);
console.log(Reflect.set(item, "id", 9));
console.log(item.id, Object.hasOwn(item, "id"));
try {
  (function () { "use strict"; item.id = 9; })();
} catch (error) {
  console.log(error.name);
}

// ✅ Expected output:
// false
// 7 false
// TypeError

Reflect.set reports false for this failed write. Strict assignment throws TypeError instead; the fixture prints the error name because engine diagnostic wording can vary. Neither path changes base.id or creates item.id.

Enumeration does not describe the whole chain

const base = { inherited: 1 };
const item = Object.create(base);
item.own = 2;
Object.defineProperty(item, "hidden", { value: 3, enumerable: false });
const symbol = Symbol("tag");
item[symbol] = 4;
const iterated = [];
for (const key in item) iterated.push(key);
console.log(Object.keys(item).join(","));
console.log(iterated.sort().join(","));
console.log(Reflect.ownKeys(item).map(key => typeof key === "symbol" ? "symbol" : key).sort().join(","));
console.log(Object.hasOwn(item, "hidden"), Object.hasOwn(item, symbol));

// ✅ Expected output:
// own
// inherited,own
// hidden,own,symbol
// true true

Object.keys covers own enumerable string keys. for...in also includes enumerable string keys inherited from prototypes. Reflect.ownKeys includes own non-enumerable and symbol keys. This example sorts the displayed labels so the lesson tests membership rather than teaching an accidental traversal order. Object Methods (keys, entries, assign, freeze) owns the broader object-method API.

const dictionary = Object.create(null);
dictionary.name = "Mina";
console.log(Object.getPrototypeOf(dictionary) === null);
console.log("toString" in dictionary, Object.hasOwn(dictionary, "name"));
dictionary.hasOwnProperty("name");

// ✅ Expected output:
// true
// false true

// ✅ Expected error:
// TypeError: dictionary.hasOwnProperty is not a function

Object.hasOwn(dictionary, "name") works without relying on a method inherited from Object.prototype. A null-prototype record can also safely have a key literally named hasOwnProperty; calling that key as if it were a trusted method would still be a mistake. A null prototype does not replace validation of allowed keys and values.

Copying values is not the same as copying method definitions

class Labelled {
  label() { return this.name.toUpperCase(); }
}
const target = { name: "mina" };
Object.assign(target, Labelled.prototype);
console.log(Object.keys(Labelled.prototype).length);
console.log(typeof target.label);

// ✅ Expected output:
// 0
// undefined

A class prototype’s ordinary methods are non-enumerable. Object.assign copies enumerable own properties, so this tempting “mixin” copies none of those methods. That is a correctness failure, not a speed comparison.

class Labelled {
  label() { return this.name.toUpperCase(); }
}
const target = { name: "mina" };
const descriptor = Object.getOwnPropertyDescriptor(Labelled.prototype, "label");
Object.defineProperty(target, "label", descriptor);
console.log(target.label());
console.log(Object.hasOwn(target, "label"), Object.keys(target).join(","));
console.log(Object.getOwnPropertyDescriptor(target, "label").enumerable);
console.log(Object.hasOwn(target, "constructor"));

// ✅ Expected output:
// MINA
// true name
// false
// false

Copy only the intended public members. Copying every descriptor blindly can overwrite constructor or an existing API. The copied function is still the same function; it does not clone closure state, reinitialize private fields, or acquire a new home for super lookup.

let reads = 0;
const source = { get amount() { reads++; return 7; } };
const assigned = Object.assign({}, source);
const described = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
console.log("reads after copies", reads);
console.log(typeof Object.getOwnPropertyDescriptor(assigned, "amount").get);
console.log(typeof Object.getOwnPropertyDescriptor(described, "amount").get);
console.log(described.amount, reads);

// ✅ Expected output:
// reads after copies 1
// undefined
// function
// 7 2

Object.assign obtains a value by reading source.amount, so its getter runs during the copy. Copying the descriptor does not read the property value. On ordinary objects this lets an inspection tool examine property shape without executing its getter. Proxies can intercept descriptor and prototype operations, so do not claim this is side-effect-free for every JavaScript value.

A copied super method still has its original home

const originalBase = { label() { return "original:" + this.name; } };
const otherBase = { label() { return "other:" + this.name; } };
const source = {
  __proto__: originalBase,
  label() { return super.label(); }
};
const target = Object.create(otherBase);
target.name = "Mina";
target.label = source.label;
console.log(target.label());
console.log(Object.getPrototypeOf(target) === otherBase);

// ✅ Expected output:
// original:Mina
// true

The copied method uses target as this, but super still starts from the prototype of the object where that method was defined. This makes arbitrary method copying unsuitable for pretending one class hierarchy has become another. The this Keyword owns receiver selection; super adds a separate lookup starting point.

class Named {
  constructor(name) { this.name = name; }
  label() { return this.name; }
}
const WithPrefix = Base => class extends Base {
  label() { return "member:" + super.label(); }
};
class Member extends WithPrefix(Named) {}
const member = new Member("Mina");
console.log(member.label());
console.log(member instanceof Named, member instanceof Member);

// ✅ Expected output:
// member:Mina
// true true

Here the returned class actually extends the supplied Base, so super has a deliberate home. The default derived constructor forwards arguments. This pattern still needs a collision policy and compatible base-class expectations. It is not evidence that inheritance or composition is always faster or always the better design.

Avoid changing shared prototypes to solve local data problems

const shared = { label() { return "old"; } };
const first = Object.create(shared);
const second = Object.create(shared);
console.log(first.label(), second.label());
shared.label = () => "new";
console.log(first.label(), second.label());
console.log(Object.hasOwn(first, "label"), Object.hasOwn(second, "label"));

// ✅ Expected output:
// old old
// new new
// false false

Both receivers still delegate to shared. Extending built-in prototypes or accepting arbitrary keys into configuration merges can therefore affect code far from the change. Keep data validation explicit and use own-property checks where inherited values are not accepted. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns the broader input and trust-boundary discussion.

This lesson makes no blanket performance ranking for factories, classes or prototype depth. Performance Optimization owns measurement of a representative workload. Use the simplest object relationship that expresses the ownership you need.

Guided exercise: find the nearest owner

Fill the literal hints. Walk until an own property is found, then report the number of prototype links traversed. A property whose value is undefined still counts as found.

const base = { value: 3 };
const middle = Object.create(base);
const item = Object.create(middle);
let current = item;
let depth = 0;
while (current !== null && !Object.___(current, "value")) { // 👉 replace ___ with hasOwn
  current = Object.___(current); // 👉 replace ___ with getPrototypeOf
  depth++;
}
console.log(depth, current === ___); // 👉 replace ___ with base

// ✅ Expected output:
// 2 true

Independent brief: inspect a property without calling its getter

Implement inspectProperty(value, key) for ordinary objects and functions, with string or symbol keys. Reject null and primitives with TypeError("value must be an object or function"); reject other key types with TypeError("key must be a string or symbol"). Walk from the object to null. Return null if absent; otherwise return depth, kind ("data" or "accessor"), enumerable and configurable, plus writable only for a data property. Do not read current[key], invoke a getter or mutate any object.

Check an own undefined value, a two-link inherited value, an accessor whose read counter stays zero, a symbol, a missing property, a null-prototype object and a function. A proxy may run traps when inspected and is outside this brief’s no-getter guarantee.

function inspectProperty(value, key) {
  if (value === null || (typeof value !== "object" && typeof value !== "function")) {
    throw new TypeError("value must be an object or function");
  }
  if (typeof key !== "string" && typeof key !== "symbol") {
    throw new TypeError("key must be a string or symbol");
  }
  let current = value;
  let depth = 0;
  while (current !== null) {
    const descriptor = Object.getOwnPropertyDescriptor(current, key);
    if (descriptor !== undefined) {
      const data = Object.hasOwn(descriptor, "value");
      const result = {
        depth,
        kind: data ? "data" : "accessor",
        enumerable: descriptor.enumerable,
        configurable: descriptor.configurable
      };
      if (data) result.writable = descriptor.writable;
      return result;
    }
    current = Object.getPrototypeOf(current);
    depth++;
  }
  return null;
}
let reads = 0;
const symbol = Symbol("tag");
const base = { inherited: 3 };
Object.defineProperty(base, "computed", { get() { reads++; return 7; }, configurable: true });
base[symbol] = 9;
const middle = Object.create(base);
const item = Object.create(middle);
item.own = undefined;
console.log(JSON.stringify(inspectProperty(item, "own")));
console.log(JSON.stringify(inspectProperty(item, "inherited")));
console.log(JSON.stringify(inspectProperty(item, "computed")), "reads", reads);
console.log(inspectProperty(item, symbol).depth);
console.log(inspectProperty(item, "missing"));
console.log(inspectProperty(Object.create(null), "toString"));
function task() {}
console.log(inspectProperty(task, "name").kind);
for (const [value, key] of [[null, "x"], [2, "x"], [{}, 4]]) {
  try { inspectProperty(value, key); }
  catch (error) { console.log(error.name, error.message); }
}
console.log(reads, Object.hasOwn(item, "computed"));

// ✅ Expected output:
// {"depth":0,"kind":"data","enumerable":true,"configurable":true,"writable":true}
// {"depth":2,"kind":"data","enumerable":true,"configurable":true,"writable":true}
// {"depth":2,"kind":"accessor","enumerable":false,"configurable":true} reads 0
// 2
// null
// null
// data
// TypeError value must be an object or function
// TypeError value must be an object or function
// TypeError key must be a string or symbol
// 0 false

Reference notes

The prototype-chain guide describes delegation. The Object.assign reference explains enumerable own values and accessor calls. The super reference distinguishes its lookup base from the call receiver.

Practice quiz

What does this complete program print? const base={value:3}; const item=Object.create(base); item.value=undefined; console.log(item.value,Object.hasOwn(item,"value"));

  • undefined true
  • 3 false
  • undefined false
  • 3 true

Answer: undefined true. An own undefined value stops property lookup.

What does this complete program print? const base={value:3}; const item=Object.create(base); console.log("value" in item,Object.hasOwn(item,"value"));

  • true true
  • true false
  • false false
  • false true

Answer: true false. in includes inherited properties; Object.hasOwn does not.

What does this complete program print? const base={get label(){return this.name}}; const item=Object.create(base);item.name="Mina"; console.log(item.label);

  • undefined
  • base
  • Mina
  • TypeError

Answer: Mina. The inherited getter receives item as this.

What does this complete program print? class A { method(){} } const item=Object.assign({},A.prototype); console.log(typeof item.method);

  • function
  • object
  • method
  • undefined

Answer: undefined. The class method is non-enumerable and is not copied by Object.assign.

What does this complete program print? const item=Object.create(null); console.log(typeof item.hasOwnProperty,Object.getPrototypeOf(item));

  • undefined null
  • function null
  • undefined undefined
  • function Object

Answer: undefined null. A null-prototype object has no inherited hasOwnProperty method.

What does this complete program print? let reads=0; const item={get value(){reads++;return 2}}; const d=Object.getOwnPropertyDescriptor(item,"value"); console.log(typeof d.get,reads);

  • number 1
  • function 0
  • function 1
  • undefined 0

Answer: function 0. Reading an ordinary object descriptor does not invoke its getter.

What does this complete program print? const base={value:1}; const a=Object.create(base),b=Object.create(base); base.value=2; console.log(a.value,b.value);

  • 1 1
  • 2 1
  • 2 2
  • 1 2

Answer: 2 2. Both objects continue to delegate to the changed shared property.

What does this complete program print? const base={};Object.defineProperty(base,"value",{value:1,writable:false}); const item=Object.create(base); console.log(Reflect.set(item,"value",2),Object.hasOwn(item,"value"));

  • true true
  • false true
  • true false
  • false false

Answer: false false. The inherited non-writable data property prevents the assignment and no own property is created.

Continue this course

Related lessons