JavaScript Object.isPrototypeOf()

Object.isPrototypeOf() 方法用于检查一个对象是否存在于另一个对象的原型链中。

示例

let obj = new Object();

// check if prototype of obj is same as // prototype of Object data type console.log(Object.prototype.isPrototypeOf(obj));
// Output: true

isPrototypeOf() 语法

isPrototypeOf() 方法的语法是:

prototypeObj.isPrototypeOf(obj)

这里,prototypeObj 指的是我们要与之比较的选定对象(obj)原型的对象。

由于 isPrototypeOf() 是一个静态方法,我们需要通过类名 Object 来访问该方法。


isPrototypeOf() 参数

isPrototypeOf() 方法接收

  • obj - 将要被检查原型链的对象

isPrototypeOf() 返回值

isPrototype() 方法返回:

  • true - 如果 prototypeObjobj 的原型
  • false - 如果 prototypeObj 不是 obj 的原型,或者 obj 本身不是一个对象

注意: isPrototypeOf()instanceof 运算符不同,它检查的是 obj 的原型链与 prototypeObj 的关系,而不是 prototypeObj.prototype


示例 1:JavaScript Object.isPrototypeOf()

// create a new instance of Object
let obj = new Object();

// check the prototype of obj
// against Object.prototype
console.log(Object.prototype.isPrototypeOf(obj)); 

// Output: true

// check the prototype of the toString method
// against Function.prototype
console.log(Function.prototype.isPrototypeOf(obj.toString));

// Output: true

// check the prototype of [2, 4, 8] array
// against Array.prototype
console.log(Array.prototype.isPrototypeOf([2, 4, 8])); 

// Output: true

在上面的示例中,我们使用了 isPrototype() 方法来检查以下对象的原型:

  • obj - 一个对象
  • obj.toString - 一个返回 obj 字符串表示形式的函数
  • [2, 4, 8] - 一个整数数组

由于 Object.prototype 是所有对象的根原型,因此我们在检查 Object.prototypeobj 时得到了 true 作为输出。

同样,

  • Function.prototype 是所有函数的原型,包括 obj.toString
  • Function.prototype 是所有数组的原型,包括 [2, 4, 8]

示例 2:isPrototypeOf() 与自定义对象

// define an object
let Animal = {
  makeSound() {
    console.log(`${this.name}, ${this.sound}!`);
  },
};

// function to create a new object
function Dog(name) {
  this.name = name;
  this.sound = "bark";

  // set prototype using setPrototypeOf()
  Object.setPrototypeOf(this, Animal);
}

// create a new object
const dog1 = new Dog("Marcus");

// check the prototype of dog1 against Animal object console.log(Animal.isPrototypeOf(dog1));
// Output: true

在上面的示例中,我们创建了两个对象:Animaldog1。请注意,dog1 对象是使用 Dog() 构造函数创建的。

使用 setPrototypeOf() 方法,我们将所有从 Dog() 构造函数创建的对象的原型设置为 Animal 的原型。

因此,我们在检查 Animal 对象是否为 dog1 的原型时得到了 true 作为输出。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战