instanceof 判断的是对象原型链是否包含构造函数的 prototype,而非数据类型;它只对对象有效,基本类型一律返回 false,核心逻辑是沿 proto 链向上查找是否匹配 right.prototype。

instanceof 判断的是原型链关系,不是数据类型
它不关心变量存的是什么值,也不管这个值看起来像数组、日期还是普通对象。它只做一件事:沿着对象的 __proto__ 链向上找,看能不能碰到构造函数的 prototype。
比如:
-
[] instanceof Array是 true,因为[].__proto__ === Array.prototype -
[] instanceof Object也是 true,因为Array.prototype.__proto__ === Object.prototype -
"hello" instanceof String是 false,字符串字面量是基本类型,没有原型链(除非显式用new String("hello"))
它只对对象有效,基本类型一律返回 false
数字、字符串、布尔、null、undefined、symbol、bigint 这些都不是对象,没有 __proto__ 属性,所以无法参与原型链查找。
即使写成 let n = 42; n instanceof Number,结果仍是 false。只有通过 new Number(42) 创建的包装对象才可能为 true —— 但实际开发中几乎不用这种方式。
手写一个 isInstanceOf 就能看清本质
核心逻辑就三步:取实例的 __proto__ → 比较是否等于构造函数的 prototype → 不等就继续往上跳,直到为 null。
简化实现如下:
function isInstanceOf(left, right) {
if (typeof left !== 'object' || left === null) return false;
let proto = left.__proto__;
while (proto) {
if (proto === right.prototype) return true;
proto = proto.__proto__;
}
return false;
}
这段代码和引擎内部做的几乎一致,只是省略了对 right.prototype 是否存在的校验。
继承场景下,instanceof 天然支持多级判断
子类实例既是子类的实例,也是父类的实例,因为原型链里包含了父类的 prototype。
例如:
class Animal {} class Dog extends Animal {}const dog = new Dog()-
dog instanceof Dog→ true -
dog instanceof Animal→ true -
dog instanceof Object→ true
这背后是完整的原型链:dog → Dog.prototype → Animal.prototype → Object.prototype → null。


















