/

The getPrototypeOf() Method in JavaScript

The getPrototypeOf() Method in JavaScript

In JavaScript, the getPrototypeOf() method is used to retrieve the prototype of an object. It allows you to access the object’s parent or prototype.

Usage

The getPrototypeOf() method is called on the Object object and takes one parameter, obj, which is the object whose prototype you want to retrieve.

1
Object.getPrototypeOf(obj)

Example

Here’s an example that demonstrates the usage of the getPrototypeOf() method:

1
2
3
4
5
const animal = {}
const dog = Object.create(animal)
const prot = Object.getPrototypeOf(dog)

console.log(animal === prot) // true

In the above code, we create an empty object animal and then create a new object dog with animal as its prototype using the Object.create() method. We then use Object.getPrototypeOf() to retrieve the prototype of dog and store it in the variable prot. In this case, the prototype of dog is animal, so animal === prot returns true.

If an object has no prototype, the getPrototypeOf() method will return null. This is the case with the Object object itself:

1
2
console.log(Object.prototype) // {}
console.log(Object.getPrototypeOf(Object.prototype)) // null

In the above code, Object.prototype is an empty object, and since it has no prototype, Object.getPrototypeOf() returns null.

By using the getPrototypeOf() method, you can access and manipulate the prototype of an object in JavaScript.

tags: [“JavaScript”, “Object”, “getPrototypeOf”, “prototype”]