Object.prototype.isPrototypeOf() 语法
isPrototypeOf() 是 JavaScript Object 对象实例中一个方法,它用于判断一个对象是否是另一个对象的原型(即是否在它的原型链上)。
语法:
prototypeObj.isPrototypeOf(obj)说明:
isPrototypeOf() 方法接收一个对象作为参数。prototypeObj.isPrototypeOf(obj) 表示判断 prototypeObj 是否存在于 obj 的原型链中。
如果参数 obj 不是对象(也就是原始值),或者 obj 是 null 或 undefined,则 isPrototypeOf() 会直接返回 false,而不会抛出异常
提示: Object.prototype.isPrototypeOf() 是 Object 原型链上的方法。也就是说,所有继承自 Object.prototype 的对象都默认拥有这个方法,并且可以通过对象实例直接调用(如 myPrototype.isPrototypeOf(myObject))。
Object.prototype.isPrototypeOf() 摘要
| 属于 | JavaScript Object 对象 |
|---|---|
| 使用频率 | 低 |
| 官方文档 | 查看 |
| MDN | 查看 |
Object.prototype.isPrototypeOf() 示例
接下来,我们通过一个简单的例子来讲解一下 isPrototypeOf() 方法是如何使用的。
示例 1:isPrototypeOf() 判断原型链上的关系
const animal = {
sleep() {
console.log("ZZZ...");
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log("汪汪汪!");
};
const myPet = Object.create(dog);
myPet.name = "大黄";
// animal 是 dog 的原型
console.log(animal.isPrototypeOf(dog));
// dog 是 myPet 的原型
console.log(dog.isPrototypeOf(myPet));
// animal 也是 myPet 的原型 (因为 animal 在 myPet 的原型链上)
console.log(animal.isPrototypeOf(myPet));
// Object.prototype 是所有对象的最终原型
console.log(Object.prototype.isPrototypeOf(myPet));运行结果如下。
true
true
true
true分析:
isPrototypeOf() 可以判断一个对象是否在另一个对象的原型链中,包括直接原型和更上层的原型。
isPrototypeOf() 与 instanceof 的区别
isPrototypeOf() 与 instanceof 都可以用于判断继承关系,但它们存在本质上的区别。
isPrototypeOf():检查的是原型链。只要 prototypeObj 存在于 obj 的原型链中(包括 obj 的直接原型、原型的原型等),就返回 true。instanceof:检查的是构造函数的 prototype 属性是否出现在实例的原型链中。它通常用于检查一个对象是否是某个类的实例。- isPrototypeOf() 可以用于任何对象(包括普通对象字面量)来判断原型关系,而 instanceof 只能用于函数(构造函数)。
示例 2:isPrototypeOf() vs instanceof
function Animal() {}
Animal.prototype.sleep = function() {
console.log("ZZZ...");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype); // Dog 继承自 Animal
Dog.prototype.constructor = Dog; // 修正构造函数指向
// 实例化对象
const myDog = new Dog();
// isPrototypeOf(): 检查原型链上是否存在
console.log(`Animal.prototype 是 myDog 的原型: ${Animal.prototype.isPrototypeOf(myDog)}`); // true
console.log(`Dog.prototype 是 myDog 的原型: ${Dog.prototype.isPrototypeOf(myDog)}`); // true
console.log(`Object.prototype 是 myDog 的原型: ${Object.prototype.isPrototypeOf(myDog)}`); // true
// instanceof: 检查构造函数的 prototype 属性是否存在于实例的原型链中
console.log(`myDog 是 Animal 的实例: ${myDog instanceof Animal}`); // true
console.log(`myDog 是 Dog 的实例: ${myDog instanceof Dog}`); // true
console.log(`myDog 是 Object 的实例: ${myDog instanceof Object}`); // true运行结果如下。
Animal.prototype 是 myDog 的原型: true
Dog.prototype 是 myDog 的原型: true
Object.prototype 是 myDog 的原型: true
myDog 是 Animal 的实例: true
myDog 是 Dog 的实例: true
myDog 是 Object 的实例: true分析:
isPrototypeOf() 更通用,可以用于任何对象来检查原型关系。而 instanceof 专注于判断一个实例是否由某个构造函数(或其继承链上的构造函数)创建的。
