📜  JavaScript Object.prototype.isPrototypeOf() 方法

📅  最后修改于: 2022-05-13 01:56:32.613000             🧑  作者: Mango

JavaScript Object.prototype.isPrototypeOf() 方法

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

句法:

prototypeObj.isPrototypeOf(object)
  • object:这是一个对象,将搜索其原型链。

返回值:布尔值。

抛出的错误:

如果prototypeObj 未定义或为空,则会引发类型错误

例子:

javascript
function obj1() {}
function obj2() {}
 
obj1.prototype = Object.create(obj2.prototype);
const obj3 = new obj1();
console.log(obj1.prototype.isPrototypeOf(obj3));
console.log(obj2.prototype.isPrototypeOf(obj3));


javascript
function A() {}
function B() {}
function C() {}
 
B.prototype = Object.create(A.prototype);
C.prototype = Object.create(B.prototype);
 
var c = new C();
 
console.log(C.prototype.isPrototypeOf(c));
console.log(B.prototype.isPrototypeOf(c));
console.log(A.prototype.isPrototypeOf(c));
console.log(Object.prototype.isPrototypeOf(c));


输出:

true
true

示例 2:此示例说明对象 c 的原型链中存在 C.prototype、B.prototype、A.prototype 和 Object.prototype:

javascript

function A() {}
function B() {}
function C() {}
 
B.prototype = Object.create(A.prototype);
C.prototype = Object.create(B.prototype);
 
var c = new C();
 
console.log(C.prototype.isPrototypeOf(c));
console.log(B.prototype.isPrototypeOf(c));
console.log(A.prototype.isPrototypeOf(c));
console.log(Object.prototype.isPrototypeOf(c));

输出:

true
true
true
true

支持的浏览器:

  • 铬 1 及以上
  • 边缘 12 及以上
  • 火狐 1 及以上
  • Internet Explorer-9 及以上
  • Opera 4 及以上
  • Safari 3 及以上