Object.setPrototypeOf(obj, proto) sets the prototype of obj to proto (or null). The object then inherits from that prototype.
For brand-new objects, prefer Object.create(proto). Changing prototypes on existing objects can be slow and hard to follow, so use setPrototypeOf only when you must.
Syntax
Call Object.setPrototypeOf() like this. Start with this line.
JavaScript
Object.setPrototypeOf(obj, proto)
Call
What it does
Object.setPrototypeOf(obj, proto)
Makes obj inherit from proto.
Object.setPrototypeOf(obj, null)
Removes the prototype chain (no inherited Object methods).
Object.create(proto)
Preferred way to make a new object with a given prototype.
proto must be an object or null. Returns obj. Fails on non-extensible objects.
Library declarations
JavaScript
Object.setPrototypeOf(obj, proto)
JavaScript
Object.setPrototypeOf(o: any, proto: object | null): any
Parameters
Parameter
Description
obj
Required. The object whose prototype you want to change.
proto
Required. The new prototype object, or null for no prototype.
Return Value
Return Value
Description
object
The same object obj, now linked to the new prototype.
JavaScript Examples
Link an Object to a Prototype
Give a user object methods from a shared prototype.
JavaScript
var personProto = {
greet: function () {
return "Hi, " + this.name;
}
};
var user = { name: "Ada" };
Object.setPrototypeOf(user, personProto);
console.log(user.greet());
console.log(Object.getPrototypeOf(user) === personProto);