Sub topic 5
Reading and Changing Prototypes: getPrototypeOf, setPrototypeOf, and __proto__
This chapter assumes you know object literals, how this is bound in method calls, and how to run code in Node.js or a browser console. It also builds on the earlier chapters: every object has a hidden [[Prototype]] link, property lookup walks the chain of those links, and Object.create sets the link when an object is created.
The [[Prototype]] link is internal, so you cannot read it as a normal property. JavaScript gives you three ways to reach it:
Object.getPrototypeOfreads the link.Object.setPrototypeOfchanges the link.__proto__is an older accessor that does both.
Reading the Link with Object.getPrototypeOf
Object.getPrototypeOf(obj) returns the object that obj inherits from, or null when the chain ends.
const animal = { eats: true };
const rabbit = Object.create(animal);
console.log(Object.getPrototypeOf(rabbit) === animal); // true
console.log(Object.getPrototypeOf(animal) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // null
// Primitives are wrapped first, so this works:
console.log(Object.getPrototypeOf('hi') === String.prototype); // true
// null and undefined cannot be wrapped:
try {
Object.getPrototypeOf(null);
} catch (e) {
console.log(e.name); // "TypeError"
}If you call Object.getPrototypeOf in a loop, you can print a whole chain:
function chainOf(obj) {
const links = [];
let current = Object.getPrototypeOf(obj);
while (current !== null) {
links.push(current === Object.prototype ? 'Object.prototype' : current);
current = Object.getPrototypeOf(current);
}
return links;
}
const base = { level: 'base' };
const mid = Object.create(base);
mid.level = 'mid';
const leaf = Object.create(mid);
console.log(chainOf(leaf));
// [ { level: 'mid' }, { level: 'base' }, 'Object.prototype' ]Changing the Link with Object.setPrototypeOf
Object.setPrototypeOf(obj, proto) replaces the prototype of an existing object and returns obj. The proto argument must be an object or null.
const walker = { walk() { return `${this.name} walks`; } };
const swimmer = { swim() { return `${this.name} swims`; } };
const duck = { name: 'Duck' };
Object.setPrototypeOf(duck, walker);
console.log(duck.walk()); // "Duck walks"
Object.setPrototypeOf(duck, swimmer);
console.log(duck.swim()); // "Duck swims"
console.log('walk' in duck); // false: the old link is goneThe object's own properties (here name) stay where they are. The only thing that changes is where lookups go after they miss on the object itself.
When setPrototypeOf Throws
Several cases throw a TypeError instead of changing the link:
// 1. A cycle in the chain
const a = {};
const b = Object.create(a);
try {
Object.setPrototypeOf(a, b); // a -> b -> a would loop forever
} catch (e) {
console.log(e.name); // "TypeError"
}
// 2. A non-extensible object (frozen, sealed, or preventExtensions)
const frozen = Object.freeze({});
try {
Object.setPrototypeOf(frozen, {});
} catch (e) {
console.log(e.name); // "TypeError"
}
// Setting the same prototype it already has is allowed:
console.log(Object.setPrototypeOf(frozen, Object.prototype) === frozen); // true
// 3. A prototype that is neither an object nor null
try {
Object.setPrototypeOf({}, 42);
} catch (e) {
console.log(e.name); // "TypeError"
}
// 4. Object.prototype itself has an immutable prototype
try {
Object.setPrototypeOf(Object.prototype, {});
} catch (e) {
console.log(e.name); // "TypeError"
}If you would rather get a result than catch an exception, use Reflect.setPrototypeOf. It returns true or false:
const sealed = Object.seal({});
console.log(Reflect.setPrototypeOf(sealed, {})); // false
console.log(Reflect.setPrototypeOf({}, null)); // trueThe Legacy __proto__ Accessor
__proto__ is a getter/setter pair defined on Object.prototype. It existed in browsers before ES2015 and was then standardized for compatibility. Reading obj.__proto__ acts like Object.getPrototypeOf(obj), and assigning to it acts like Object.setPrototypeOf, with some differences:
const proto = { greet() { return 'hi'; } };
const obj = {};
obj.__proto__ = proto;
console.log(obj.greet()); // "hi"
obj.__proto__ = 42; // silently ignored, no error
console.log(Object.getPrototypeOf(obj) === proto); // true
// The accessor lives on Object.prototype, so objects that do not
// inherit from it have no special __proto__ at all:
const bare = Object.create(null);
bare.__proto__ = proto; // creates an ordinary own property
console.log(typeof bare.greet); // "undefined"
console.log(Object.keys(bare)); // [ '__proto__' ]The accessor depends on the object having Object.prototype somewhere in its chain, and it silently ignores invalid values. Both of these make bugs harder to spot. Do not use it in new code.
__proto__ in Object Literals Is Different
Inside an object literal, __proto__: value is separate syntax. It sets the prototype of the new object directly and does not call the accessor. This form is widely used and works well:
const proto = { kind: 'proto' };
const viaLiteral = { __proto__: proto, name: 'x' };
console.log(Object.getPrototypeOf(viaLiteral) === proto); // true
console.log(Object.hasOwn(viaLiteral, '__proto__')); // false
// A computed key is NOT the special syntax: it creates an own property
const computed = { ['__proto__']: proto };
console.log(Object.getPrototypeOf(computed) === Object.prototype); // true
console.log(Object.hasOwn(computed, '__proto__')); // true
// JSON.parse also creates an own property named "__proto__"
const parsed = JSON.parse('{"__proto__": {"admin": true}}');
console.log(parsed.admin); // undefined
console.log(Object.hasOwn(parsed, '__proto__')); // trueChoosing the Right Tool
| Task | Preferred | Avoid |
|---|---|---|
| Read a prototype | `Object.getPrototypeOf(obj)` | `obj.__proto__` |
| Create an object with a given prototype | `Object.create(proto)` or `{ __proto__: proto }` | Creating, then calling `setPrototypeOf` |
| Change a prototype, throwing on failure | `Object.setPrototypeOf(obj, proto)` | `obj.__proto__ = proto` |
| Change a prototype, getting a boolean result | `Reflect.setPrototypeOf(obj, proto)` | Wrapping `setPrototypeOf` in try/catch just to test |
Common Errors
- Reading
obj.__proto__on a null-prototype object and gettingundefinedor an own property, not the real prototype. - Expecting
obj.__proto__ = 'string'to throw. It is ignored without any error. - Calling
setPrototypeOfon a frozen object from a library and getting aTypeError. - Confusing
Object.getPrototypeOf(fn)(for a plain function this isFunction.prototype) withfn.prototype, which is the object that instances of a constructor will inherit from. Constructor functions are covered in a later chapter.
Exercise
Predict the output of each line: const p = { x: 1 }; const o = Object.create(null); o.__proto__ = p; console.log(o.x); Object.setPrototypeOf(o, p); console.log(o.x); console.log(Object.hasOwn(o, '__proto__'));
Show answer
undefined, then 1, then true. Because o has no Object.prototype in its chain, o.__proto__ = p creates an own property named __proto__ and does not change the link, so o.x is undefined. Object.setPrototypeOf sets the real link, so o.x becomes 1. The own __proto__ property created by the first assignment is still there, so Object.hasOwn returns true.
Exercise
Write a function safeSetProto(obj, proto) that returns true if the prototype was changed and false otherwise (non-extensible object, cycle, or invalid proto), without using try/catch.
Show answer
Validate the argument types, then let Reflect.setPrototypeOf report the result: function safeSetProto(obj, proto) { if (typeof proto !== 'object' && typeof proto !== 'function') return false; if (Object(obj) !== obj) return false; return Reflect.setPrototypeOf(obj, proto); }. typeof null is 'object', so null passes the first check, which is what you want. Reflect.setPrototypeOf returns false for cycles and non-extensible objects. It throws only when the target is not an object or the prototype is invalid, and the guards rule out both.