Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Object

Object.setPrototypeOf()

Reference for JavaScript Object.setPrototypeOf(): change the prototype of an existing object, with its exceptions, cycles and performance cost.

Object.setPrototypeOf() replaces the prototype of an existing object. After the call, property lookups that fail on the object continue on the new prototype.

It is the standard replacement for the old __proto__ assignment. It works, but changing a prototype after an object exists is slow in engines and rarely necessary. When you can, choose the prototype at creation time with Object.create(), a class or a constructor.

JavaScript
Object.setPrototypeOf(obj, proto);

Try it

JS Swapping the prototype

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Things that throw

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Object.setPrototypeOf(obj, prototype)
Name Description
obj The object whose prototype is changed.
prototype The new prototype: an object or null.

Return value: obj. If obj is a primitive, it is returned unchanged and nothing is modified.

Exceptions: a TypeError if prototype is neither an object nor null, if obj is null or undefined, if obj is non-extensible, or if the change would create a cycle in the prototype chain. Some exotic objects, such as Object.prototype itself, have immutable prototypes and also throw.

Usage notes

  • Performance. Changing the prototype of an object that has already been used invalidates engine optimizations for it and for objects that inherit from it. Avoid it in hot code.
  • Prefer creation-time choices. Object.create(proto) and class ... extends set the prototype once, cleanly.
  • __proto__ is the legacy accessor for the same operation. Prefer the Object methods in new code.
  • Not a copy. The object keeps its own properties; only the inherited ones change.
  • Valid uses: setting up inheritance between existing objects, or in tooling and polyfills that must patch objects in place.
  • Setting null gives an object with no inherited methods, similar to Object.create(null), but with the speed caveat above.

Browser support

Object.setPrototypeOf() is available in every current browser and JavaScript runtime.