Skip to content

Latest commit

 

History

History
103 lines (80 loc) · 2.61 KB

File metadata and controls

103 lines (80 loc) · 2.61 KB
title ms.custom ms.date ms.prod ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic dev_langs ms.assetid caps.latest.revision author ms.author manager
Object.setPrototypeOf Function (JavaScript) | Microsoft Docs
01/18/2017
windows-client-threshold
devlang-javascript
language-reference
JavaScript
TypeScript
DHTML
a2609f6e-aeee-4c13-b7cf-c31ddf58ff35
3
mikejo5000
mikejo
ghogen

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

[!INCLUDEjsv12]