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
Object.getPrototypeOf
Returns the prototype (i.e. the internal [[Prototype]]) of the specified object, or null if it has none. Preferred over the legacy __proto__ accessor.
Object.create
Creates a new object with the specified prototype and optional property descriptors. Pass null to create an object with no prototype at all.
Object.preventExtensions
Prevents new properties from being added to an object, but existing properties can still be modified, deleted, or reconfigured. The weakest of the three protection levels.