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.
Object.setPrototypeOf(obj, proto);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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)andclass ... extendsset the prototype once, cleanly. __proto__is the legacy accessor for the same operation. Prefer theObjectmethods 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
nullgives an object with no inherited methods, similar toObject.create(null), but with the speed caveat above.
Browser support
Object.setPrototypeOf() is available in every current browser and JavaScript runtime.
Related
Object.getPrototypeOf(),Object.create()- Concept: prototypes and the prototype chain
- Lessons: Prototypes, Inheritance