📜  isPrototypeOf js - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:27.299000             🧑  作者: Mango

isPrototypeOf in JavaScript

isPrototypeOf is a built-in method in JavaScript that checks if an object exists in another object's prototype chain. It is commonly used to check if an instance was created from a particular constructor function.

Syntax

The syntax for isPrototypeOf is as follows:

prototypeObj.isPrototypeOf(object)

Here, prototypeObj is the object that should be found in the prototype chain, and object is the object whose prototype chain should be searched. The method returns true if prototypeObj is found in the prototype chain of object, and false otherwise.

Example
function Person(name) {
  this.name = name;
}

const person1 = new Person('John');
const person2 = new Person('Jane');

console.log(Person.prototype.isPrototypeOf(person1)); // true
console.log(Person.prototype.isPrototypeOf(person2)); // true
console.log(Object.prototype.isPrototypeOf(person1)); // true

In the above example, we create a Person constructor function and then create two object instances person1 and person2 using the new keyword. We then use isPrototypeOf to check if Person.prototype is in the prototype chain of person1 and person2, which returns true in both cases.

We also use isPrototypeOf to check if Object.prototype is in the prototype chain of person1, which also returns true since all JavaScript objects inherit from Object.prototype.

Conclusion

isPrototypeOf is an important method in JavaScript that is used to check an object's prototype chain. Learning how to use it is essential for any JavaScript developer.