JavaScript Object.setPrototypeOf Explained With Examples
Object.setPrototypeOf() changes the prototype of an existing object. See its errors, the cycle check, null prototypes and when Object.create wins.

Most prototype chains are decided at the moment an object is created, through Object.create(), a constructor or a class. Object.setPrototypeOf() is the escape hatch for the other case: the object already exists, and you want to change what it inherits from. It works, it is standard, and the documentation around it still carries a warning about performance that you should read before you use it in a loop. This post covers the call itself, the errors it raises, and the situations where it is the right choice. The reading side is [the post on Object.getPrototypeOf()](/library/javascript-object-getprototypeof). Examples run on Node.js 24, and the method has existed since ES2015.
What Object.setPrototypeOf() takes and returns
The signature is Object.setPrototypeOf(obj, prototype). The first argument is the object to change. The second must be either an object or null. The call changes the object in place and returns the same object, so you can use it inside an expression.
| Argument | Rule |
|---|---|
obj an object | Its internal prototype is replaced |
obj a primitive | Returned unchanged, nothing happens |
obj is null or undefined | Throws a TypeError |
prototype an object | Becomes the new prototype |
prototype is null | The object has no prototype |
prototype anything else | Throws a TypeError |
const animal = {
speak() {
return `${this.name} makes a sound`;
},
};
const dog = { name: "Rex" };
const result = Object.setPrototypeOf(dog, animal);
console.log(result === dog);
console.log(dog.speak());
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.keys(dog));true
Rex makes a sound
true
[ 'name' ]The method speak is not an own property of dog, which the last line confirms, but property lookup walks to animal and finds it. this is dog at the call site, so the template reads dog.name.
Replacing the chain, not adding to it
The new prototype replaces the old one. Anything the object inherited before is no longer reachable through the chain unless the new prototype also inherits it.
const plain = { id: 1 };
console.log(typeof plain.toString);
console.log(plain.hasOwnProperty("id"));
Object.setPrototypeOf(plain, null);
console.log(typeof plain.toString);
console.log(plain);function
true
undefined
[Object: null prototype] { id: 1 }Passing null strips away Object.prototype, so toString, hasOwnProperty and the rest vanish from the object. That is the point of a dictionary-style object that cannot collide with built-in names, and it is also why a null-prototype object breaks code that calls obj.hasOwnProperty(key). Use Object.hasOwn(obj, key) instead, as covered in [the post on Object.hasOwn()](/library/javascript-object-hasown). Node.js prints the missing prototype in the header of the output, which makes these objects easy to spot in logs.
The errors it can raise
There are four distinct failures. We list the V8 messages, but the wording belongs to the engine, so catch the error class and not the text.
function attempt(label, fn) {
try {
fn();
console.log(label, "ok");
} catch (err) {
console.log(label, err.name + ":", err.message);
}
}
attempt("bad proto", () => Object.setPrototypeOf({}, 42));
attempt("undefined target", () => Object.setPrototypeOf(undefined, {}));
const a = {};
const b = Object.setPrototypeOf({}, a);
attempt("cycle", () => Object.setPrototypeOf(a, b));
const locked = Object.preventExtensions({});
attempt("locked", () => Object.setPrototypeOf(locked, {}));bad proto TypeError: Object prototype may only be an Object or null: 42
undefined target TypeError: Object.setPrototypeOf called on null or undefined
cycle TypeError: Cyclic __proto__ value
locked TypeError: #<Object> is not extensibleThe cycle check is worth remembering. A chain that loops back on itself would make property lookup run forever, so the engine refuses it. The non-extensible case comes from Object.preventExtensions(), Object.seal() and Object.freeze(), all of which fix the prototype along with the shape. Setting the prototype to the value it already has does not throw, even on a frozen object, because nothing changes.
If you would rather get a boolean than an exception, Reflect.setPrototypeOf() takes the same arguments and returns false where Object.setPrototypeOf() would throw for an extensibility or cycle problem.
const frozen = Object.freeze({});
console.log(Reflect.setPrototypeOf(frozen, { x: 1 }));
console.log(Reflect.setPrototypeOf({}, { y: 2 }));
console.log(Reflect.setPrototypeOf(frozen, Object.prototype));false
true
trueThe third line passes the prototype the frozen object already has, so it succeeds.
Primitives are left alone
If the first argument is a primitive, the call returns it and does nothing else. Before ES2015 this threw, and that older behavior still appears in tutorials.
const text = Object.setPrototypeOf("hello", { extra: true });
console.log(text);
console.log(typeof text);
console.log(text.extra);
console.log(text.length);hello
string
undefined
5The string is not wrapped in an object that would carry the new prototype. The length of 5 comes from the ordinary string wrapper, which proves nothing changed. If you want a boxed value with a custom chain, create the wrapper yourself with Object(value) and set the prototype on that.
Classic inheritance with constructor functions
Before class syntax, the standard way to wire a subclass was to point the child's prototype at the parent's. Object.setPrototypeOf() does that without replacing the whole prototype object, which means the constructor property survives.
function Animal(name) {
this.name = name;
}
Animal.prototype.describe = function () {
return `${this.name} is an animal`;
};
function Cat(name) {
Animal.call(this, name);
}
Object.setPrototypeOf(Cat.prototype, Animal.prototype);
Cat.prototype.purr = function () {
return `${this.name} purrs`;
};
const tom = new Cat("Tom");
console.log(tom.describe());
console.log(tom.purr());
console.log(tom instanceof Animal);
console.log(Cat.prototype.constructor === Cat);Tom is an animal
Tom purrs
true
trueThe older idiom Cat.prototype = Object.create(Animal.prototype) works too, but it discards the default constructor property and you have to put it back. In new code, class Cat extends Animal does all of this and reads better. We reach for the function form only when maintaining code that has not been converted.
Retrofitting an existing array
Another legitimate use is giving an object extra behavior after something else created it, such as an array that came out of a parser. Assigning a new prototype keeps the array exotic behavior intact, because that behavior is tied to the object and not to its prototype.
class Stack extends Array {
peek() {
return this[this.length - 1];
}
}
const raw = [1, 2, 3];
Object.setPrototypeOf(raw, Stack.prototype);
console.log(raw.peek());
console.log(raw instanceof Stack);
console.log(Array.isArray(raw));
console.log(raw.length);
raw.push(4);
console.log(raw.length);3
true
true
3
4The array stayed a real array, length still updates, and the new method resolves through the chain. That said, Stack.from(raw) makes a proper instance without touching the original, and it is the cleaner route when you can afford the copy.
A mistake we made: calling it in a hot path
We attached a prototype with shared methods to every row of a result set as it arrived, using Object.setPrototypeOf(row, RowMethods) inside the mapping loop. It worked, and a profile later showed the work concentrated there. The MDN page warns about this: engines optimize property access on the assumption that an object's prototype does not change, so mutating it after creation can deoptimize every code path that touches the object. We cannot give you a number for your workload, so measure it. The fix was to build rows with a factory that used Object.create(RowMethods), or a class, so the prototype was correct from the start.
const RowMethods = {
label() {
return `#${this.id}`;
},
};
const rows = [{ id: 1 }, { id: 2 }].map((data) =>
Object.assign(Object.create(RowMethods), data)
);
console.log(rows.map((r) => r.label()));
console.log(Object.getPrototypeOf(rows[0]) === RowMethods);[ '#1', '#2' ]
trueComparing the ways to set a prototype
| Approach | When the prototype is set | Notes |
|---|---|---|
Object.create(proto) | At creation | Preferred for new objects |
class A extends B | At definition | Best for named hierarchies |
{ __proto__: proto } literal | At creation | Standard syntax in object literals |
Object.setPrototypeOf() | After creation | Works on any extensible object |
Assigning obj.__proto__ | After creation | Legacy accessor, avoid in new code |
const base = { kind: "base" };
const viaCreate = Object.create(base);
const viaLiteral = { __proto__: base, own: 1 };
const viaSet = Object.setPrototypeOf({ own: 2 }, base);
console.log(viaCreate.kind, viaLiteral.kind, viaSet.kind);
console.log(Object.keys(viaLiteral), Object.keys(viaSet));base base base
[ 'own' ] [ 'own' ]The literal form with __proto__ is part of the standard and is not the same thing as assigning to obj.__proto__ later. Both are described in [the post on Object.create()](/library/javascript-object-create).
Reading the result back
After you change a prototype, three checks confirm what happened. Object.getPrototypeOf(obj) returns the new prototype, proto.isPrototypeOf(obj) answers the same question from the other side, and obj instanceof Constructor consults the prototype property of a constructor. They can disagree. An object can have a given prototype in its chain while failing instanceof, because instanceof compares against whatever the constructor's prototype property points to at that moment, and it knows nothing about how the chain was built.
That matters when you retrofit behavior. If you set the prototype of an object to Stack.prototype, then instanceof Stack is true, since the chain contains that object. If you instead set it to a plain object that merely has the same methods, the behavior is the same but instanceof is false. Pick the check your callers use and make sure the prototype you assign satisfies it.
Finally, the change is visible to every reader of the object immediately, including code that cached a method reference earlier. A function you copied out before the change keeps pointing at the old method, while a fresh lookup finds the new one. Keep that in mind in long-lived objects that other modules hold onto.
Where Object.setPrototypeOf() stops being the right tool
Use it for retrofitting and for tooling code that must change an object it did not create. Do not use it for objects you construct yourself, because there is always a way to set the prototype at creation time, and that path is both clearer and friendlier to the engine. Do not use it to emulate multiple inheritance or to swap behavior at runtime, since a chain that changes under a running program is hard to reason about and impossible to type check.
It also cannot help with objects that are frozen or non-extensible, with primitives, or with cyclic requirements. For those, copy into a new object with the prototype you want, or compose with delegation and keep the relationship explicit in a property.
The method is specified at Object.setPrototypeOf in ECMAScript and documented on the MDN Object.setPrototypeOf page.


