mutation

Object.setPrototypeOf

Sets the prototype (i.e. the [[Prototype]]) of a specified object to another object or null. Considered a slow operation and generally discouraged — prefer Object.create at construction time.

Object.setPrototypeOf(obj, proto)

Parameters

Parameter Purpose
obj The object to modify
proto The new prototype (an object or null)
returns The mutated object

Examples

const o = {};
Object.setPrototypeOf(o, { greet: () => 'hi' });
console.log(o.greet());

Logs 'hi'

const o = { a: 1 };
Object.setPrototypeOf(o, null);
console.log(Object.getPrototypeOf(o));

Logs null — detaches from Object.prototype

const frozen = Object.freeze({});
try { Object.setPrototypeOf(frozen, {}); } catch (e) { console.log(e.name); }

Logs 'TypeError' — non-extensible objects reject prototype changes

class A { hello() { return 'A'; } }
class B {}
const b = new B();
Object.setPrototypeOf(b, A.prototype);
console.log(b.hello());

Logs 'A'

Gotcha

Modifying an object's prototype after creation deoptimizes many JS engines — prefer Object.create(proto) at construction time. Throws TypeError on non-extensible or frozen objects.

Related methods

← All JS Object methods · Array methods · Spread vs rest