setPrototypeOf()

The static Reflect.setPrototypeOf function is utilized to assign the prototype of a given object to a different object. The initial parameter represents the object reference, while the subsequent parameter may either be null or another object. This method operates identically to the Object.setPrototypeOf function.

Syntax:

Example

Reflect.setPrototypeOf(obj, prototype)

Parameters:

Obj: This refers to the target object for which the prototype is to be established.

Prototype : It is the object's new prototype.

Return value:

This approach yields a Boolean value that signifies whether the prototype was established successfully or not.

Exceptions:

A TypeError, if the target is not an Object

Browser Support:

Chrome 49
Edge 12
Firefox 42
Opera 36

Example 1

Example

const object = {};
console.log(Reflect.setPrototypeOf(Object.freeze(object), null));

Output:

Example 2

Example

var Animal = {
   speak() {
     console.log(this.name + ' makes a noise.');
   }
};
class g {
   constructor(name) {
   this.name = name;
  }
}
Reflect.setPrototypeOf(g.prototype, Animal);
// If you do not do this you will get a TypeError when you invoke speak
var d = new g('Mitzie');
d.speak();

Output:

Output

"Mitzie makes a noise."

Example 3

Example

let toyota = {
  drive() {
    return 'value';
  }
}
let obj = {
  wifi() {
    return 'answer';
  }
}
Object.setPrototypeOf(obj, toyota);
console.dir(obj); 
document.write(obj.wifi());
document.writeln("<br/>");
document.writeln(obj.drive());

Output:

Output

answer
value

Input Required

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