Object.setPrototypeOf() method

The Object.setPrototypeOf function is utilized to assign the prototype (which refers to the internal [[Prototype]] property) of a designated object to either another object or null. In JavaScript, every object derives properties and methods from its prototype. This method is widely regarded as the appropriate approach for establishing the prototype of an object.

Syntax:

Example

Object.setPrototypeOf(obj, prototype)

Parameters:

obj: This refers to the object for which the prototype is intended to be established.

Prototype: This refers to the new prototype of the object, which can either be another object or a null value.

Return value:

This method returns the specified object.

Browser Support:

Chrome 34
Edge Yes
Firefox 31
Opera Yes

Example 1

Example

let raay = {
  drive() {
    return 'Add raay';
  }
}
let naty  = {
  net() {
    return 'use net';
  }
}
// Set raay's __proto__ to naty's  __proto__'s  __proto__
Object.setPrototypeOf(naty, raay);

console.dir(naty); //prints the naty object
console.log(naty.net()); // use net
console.log(naty.drive()); // Add raay

Output:

Output

[object Object] {
  drive: drive() {
    return 'Add raay';
  },
  net: net() {
    return 'use net';
  }
}
"use net"
"Add raay"

Example 2

Example

var Animal = {
   speak() {
     console.log(this.name + ' makes');
   }
};

class Dog {
   constructor(name) {
   this.name = name;
  }
}

Object.setPrototypeOf(Dog.prototype, Animal); 
// If you do not do this you will get a TypeError when you invoke speak
var d = new Dog('people');
d.speak();

Output:

Output

"people makes"

Example 3

Example

let toyota = {
  drive() {
    return 'driving toyota';
 }
}
let camry = {
  wifi() {
    return 'carry';
  }
}
// Set toyota's __proto__ to camry's  __proto__'s  __proto__
Object.setPrototypeOf(camry, toyota);
console.dir(camry); //prints the camry object
console.log(camry.wifi()); // carry

Output:

Output

[object Object] {
 drive: drive() {
    return 'driving toyota';
 },
  wifi: wifi() {
    return 'carry';
  }
}
"carry"

Input Required

This code uses input(). Please provide values below: