javascript 中判断实例与原型链关系应使用 instanceof 运算符,它通过检查对象的原型链是否包含构造函数 prototype 属性来返回布尔值。具体做法是将实例对象放在左侧,构造函数放在右侧,例如 obj instanceof constructor。该机制能准确识别继承关系,但需注意 object.prototype.tostring.call() 在跨 iframe 或不同执行上下文时可能失效,而 instanceof 同样受此限制。

instanceof 如何检测原型链
instanceof 的核心逻辑是遍历对象的 [[Prototype]](即 __proto__),直到找到目标构造函数的 prototype 属性或到达 null。如果找到则返回 true,否则返回 false。这意味着只要对象在原型链上,即使不是直接实例,也会返回 true。

class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
const myDog = new Dog('Rex', 'Labrador');
console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true
console.log(myDog instanceof String); // false
上述代码定义了 Animal 和继承自它的 Dog 类。创建 myDog 实例后,instanceof 检查显示它在原型链上同时属于 Dog、Animal 和 Object,但不属于 String。
自定义 Symbol.hasInstance 改变行为
ES6 引入了 Symbol.hasInstance,允许自定义 instanceof 的判断逻辑。通过在构造函数上定义该符号属性为一个函数,可以覆盖默认的 [[HasInstance]] 方法。这使得 instanceof 不再仅仅依赖原型链,而是根据自定义逻辑返回结果。
你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型

class CustomChecker {
static [Symbol.hasInstance](obj) {
return typeof obj === 'number';
}
}
console.log(42 instanceof CustomChecker); // true
console.log('42' instanceof CustomChecker); // false
console.log({} instanceof CustomChecker); // false
这段代码重写了 CustomChecker 的 hasInstance 行为,使其对任何数字类型都返回 true,无论其原型链如何。这展示了 instanceof 的动态可配置性。
基于 null 输入的条件判断结果
当 instanceof 左侧操作数为 null 时,结果始终为 false。这是因为 null 没有原型链,无法进行遍历查找。这是 instanceof 在处理空值时的确定性行为,开发者需在使用前确保对象非空,以避免意外返回 false。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










