Object.setPrototypeOf Function (JavaScript)

Sets the prototype of an object.

Syntax

Object.setPrototypeOf(obj, proto);  

Parameters

obj
Required. The object for which you are setting the prototype.

proto
Required. The new prototype object.

Remarks

Warning

Setting the prototype may reduce performance on all JavaScript code that has access to an object whose prototype has been mutated.

Example

The following code example shows how to set the prototype for an object.

function Rectangle() {  
}  

var rec = new Rectangle();  

if (console && console.log) {  
    console.log(Object.setPrototypeOf(rec) === Rectangle.prototype);  // Returns true  
    Object.getPrototypeOf(rec, Object.prototype);  
    console.log(Object.setPrototypeOf(rec) === Rectangle.prototype);  // Returns false  
}  

Example

The following code example shows how to add properties to an object by adding them to the prototype.

var proto = { y: 2 };  

var obj = { x: 10 };  
Object.setPrototypeOf(obj, proto);  

proto.y = 20;  
proto.z = 40;  

if (console && console.log) {  
    console.log(obj.x === 10);  // Returns true  
    console.log(obj.y === 20);  // Returns true  
    console.log(obj.z === 40);  // Returns true  
}  

Example

The following code example adds properties to the String object by setting a new prototype on it.

var stringProp = { desc: "description" };  

Object.setPrototypeOf(String, stringProp);  
var s1 = "333";  
var s2 = new String("333");  

if (console && console.log) {  

    console.log(String.desc === "description"); // Returns true  
    console.log(s1.desc === "description");     // Returns false  
    console.log(s2.desc === "description");     // Returns false  

    Object.setPrototypeOf(s1, String); // Can't be set.  
    Object.setPrototypeOf(s2, String);  

    console.log(s1.desc === "description"); // Returns false  
    console.log(s2.desc === "description"); // Returns true  
}  

Requirements

Supported in Microsoft Edge (Edge browser). Also supported in Store apps (Microsoft Edge on Windows 10). See Version Information.
Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Not supported in Windows 8.1.