| 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 |
|
language-reference |
|
a2609f6e-aeee-4c13-b7cf-c31ddf58ff35 |
3 |
mikejo5000 |
mikejo |
ghogen |
Sets the prototype of an object.
Object.setPrototypeOf(obj, proto);
obj
Required. The object for which you are setting the prototype.
proto
Required. The new prototype object.
Warning
Setting the prototype may reduce performance on all JavaScript code that has access to an object whose prototype has been mutated.
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
} 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
} 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
} [!INCLUDEjsv12]