Prototype Features in JavaScript

Introduction

Beyond prototypes basics, the language exposes tools to inspect and adjust prototype links: hasOwnProperty, the in operator, Object.getPrototypeOf, and Object.create. These features power debugging, safe copying, and library design.

Prerequisites

Own vs Inherited Properties

javascript
const animal = { eats: true };
const rabbit = Object.create(animal);
rabbit.jumps = true;
 
console.log(rabbit.jumps);
console.log(rabbit.eats);
console.log(rabbit.hasOwnProperty("jumps"));
console.log(rabbit.hasOwnProperty("eats"));

in Operator

javascript
// true if property exists anywhere on chain
console.log("eats" in rabbit);
console.log("toString" in rabbit);

Prefer hasOwnProperty or Object.hasOwn when you only care about own keys.

Object.hasOwn (Modern)

javascript
// Replaces hasOwnProperty call on object
console.log(Object.hasOwn(rabbit, "jumps"));
console.log(Object.hasOwn(rabbit, "eats"));

Walk Prototype Chain

javascript
// getPrototypeOf follows links
let obj = rabbit;
while (obj) {
  console.log(obj);
  obj = Object.getPrototypeOf(obj);
}

Ends at null after Object.prototype.

Object.create(proto)

javascript
// New object with chosen prototype
const proto = {
  greet() {
    return `Hello, ${this.name}`;
  },
};
 
const user = Object.create(proto);
user.name = "Lin";
console.log(user.greet());

Changing Prototype (Rare)

javascript
// setPrototypeOf — use sparingly for performance/clarity
const a = { x: 1 };
const b = { y: 2 };
Object.setPrototypeOf(a, b);
 
console.log(a.y);

Prefer class extends for hierarchies in application code.

instanceof

javascript
class Dog {}
const d = new Dog();
 
console.log(d instanceof Dog);
console.log(d instanceof Object);

Checks prototype chain, not class name strings.

Mini Example: Safe Own-Key Copy

javascript
function pickOwn(obj, keys) {
  const result = {};
  for (const key of keys) {
    if (Object.hasOwn(obj, key)) {
      result[key] = obj[key];
    }
  }
  return result;
}
 
const source = { a: 1, b: 2 };
Object.setPrototypeOf(source, { c: 3 });
 
console.log(pickOwn(source, ["a", "b", "c"]));

FAQ

__proto__?

Legacy accessor—use Object.getPrototypeOf in new code.

Can I delete inherited properties?

Only own properties—delete rabbit.eats does not remove animal.eats.

Prototype vs class extends?

extends sets up the chain; these APIs inspect or tweak it.

What comes next?

Symbols.