The isPrototypeOf()
method of the Object
class in Javascript checks if an object is another object’s prototype. To determine the class of an object, the isPrototypeOf()
method checks the entire prototype chain of the other object.
The process is illustrated below:
To use the isPrototypeOf()
method, you will need to use the following command:
firstObj.isPrototypeOf(secondObj);
In the code shown above, firstObj
and secondObj
represent an instance of the Object
class.
The isPrototypeOf()
method takes a single mandatory parameter, i.e., the object whose prototype chain must be checked.
The isPrototypeOf()
method returns true
if firstObj
is the prototype of secondObj
; otherwise, it returns false
.
The code below shows how the isPrototypeOf()
method works in Javascript:
// initializing objectsvar objOne = new Object();function func(){};var array = [5, 10, 20];// checking valid prototype chainsconsole.log(Object.prototype.isPrototypeOf(objOne));console.log(Function.prototype.isPrototypeOf(func));console.log(Array.prototype.isPrototypeOf(array));//checking invalid prototype chainsconsole.log(Function.prototype.isPrototypeOf(array));console.log(Array.prototype.isPrototypeOf(objOne));
First, the code initializes an empty object
, function
, and array
. The isPrototypeOf()
method is then used to evaluate the prototype chains of different combinations of classes and variables.
The first calls to the isPrototypeOf()
method all return true
because the objects objOne
, func
, and array
are prototypes of the Object
, Function
, and Array
classes, respectively.
On the other hand, the isPrototypeOf()
method in line returns false
because array
belongs to the Array
class but not the Function
class. Similarly, the isPrototypeOf()
method in line also returns false
, as objOne
is not a Function
prototype, but rather an Object
.
Free Resources