💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# instanceof ## 概念 `instanceof` 运算符用于测试 **构造函数** 的 `prototype` 属性是否出现在对象的原型链中的**任何位置** ~~~ function M() {} var obj = new M() obj.__proto__ === M.prototype // true obj instanceof M // true M.prototype.__proto__ === Object.prototype // true M instanceof Object // true ~~~ <br> <br> ~~~ // 定义构造函数 function C(){} function D(){} var o = new C(); o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype o instanceof D; // false,因为 D.prototype不在o的原型链上 o instanceof Object; // true,因为Object.prototype.isPrototypeOf(o)返回true C.prototype instanceof Object // true,同上 C.prototype = {}; var o2 = new C(); o2 instanceof C; // true o instanceof C; // false,C.prototype指向了一个空对象,这个空对象不在o的原型链上. D.prototype = new C(); // 继承 var o3 = new D(); o3 instanceof D; // true o3 instanceof C; // true 因为C.prototype现在在o3的原型链上 ~~~ <br> ## 判断对象是否是某个构造函数的实例 ~~~ function M() {} var obj = new M() obj.__proto__.constructor === M //true obj.__proto__.constructor === Object //true ~~~ ## 模拟instanceof ~~~ function myinstanceOf(left, right) { let prototype = right.prototype left = left.__proto__ while (true) { if (left === prototype) { return true } if (left === null || left === undefined) { return false } left = left.__proto__ } } ~~~