JavaScript Object.getPrototypeOf()


The Object.getPrototypeOf() method returns the prototype of the specified object.

Example


getPrototypeOf() syntax

The syntax of the getPrototypeOf() method is:

Object.getPrototypeOf(obj)

Here, getPrototypeOf() is a static method. Hence, we need to access the method using the class name, Object.


getPrototypeOf() Parameters

The getPrototypeOf() method takes in:

  • obj - the object whose prototype is to be returned.

getPrototypeOf() Return Value

The getPrototypeOf() method returns:

  • the prototype of the given object.
  • null if there are no inherited properties.

Note: The getPrototypeOf() method throws a TypeError exception if the obj parameter isn't an object in ES5. However, since ES2015, the parameter will be coerced to an Object and won't throw any exception.


Example 1: Javascript Object.getPrototypeOf()

In this example, we have created a custom object named person. Then, we used the getPrototypeOf() method to print its prototype.

As can be seen from the output, the prototype of the person is an empty object {}.

Note: By default, objects inherit from Object.prototype. And the prototype of Object.prototype is an empty object {}, which is also the ultimate prototype for all objects in JavaScript.


Example 2: getPrototypeOf() With setPrototypeOf()

In the above example, we first created an empty object obj and a non-empty object person.

We then used the setPrototypeOf() method to set the prototype of the empty object to that of the person object.

When we use the getPrototypeOf() method to print the prototype of obj, we get the person object as an output.

Thus, the prototype of obj is the person object.

This is confirmed when we check the prototype of obj against the person object using a Boolean expression, which returns true.

// Boolean expression returns true
Object.getPrototypeOf(obj) == person

Example 3: getPrototypeOf() to Find Prototype of String

In the above example, we called Object.getPrototypeOf() to get the prototype of the string str.

The output indicates that the prototype of str is the String constructor function.


Example 4: getPrototypeOf() to Find Prototype of Function

In the above example, we have created a function greet() which prints "Hello!" when called.

We get [Function] as an output when using the getPrototypeOf() method to find the prototype of greet() function.

This output indicates that the prototype of greet() is the [Function] constructor function.


Recommended Reading: