JavaScript 中构造函数怎么判断 instanceof
在 javascript 中,instanceof 运算符通过检查构造函数的 prototype 属性是否出现在对象的原型链上来进行判断。具体做法是:obj instanceof constructor,如果 constructor.prototype 存在于 obj 的原型链上,则返回 true,否则返回 false。

instanceof 如何遍历原型链
instanceof 的判断过程是从对象的 __proto__(即内部原型)开始,沿着原型链向上查找,直到找到与构造函数 prototype 相同的对象为止。如果到达原型链顶端(null)仍未找到,则返回 false。

function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice instanceof Person); // true
console.log(alice instanceof Object); // true
console.log(alice instanceof Array); // false
instanceof 在不同继承场景下的表现
当涉及继承时,instanceof 会同时检查父类和子类的原型。例如,子类实例既是子类的实例,也是父类的实例,因为子类的原型链中包含父类的原型。

class Animal {
constructor(species) {
this.species = species;
}
}
class Dog extends Animal {
constructor(name) {
super('Canine');
this.name = name;
}
}
const dog = new Dog('Buddy');
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(dog instanceof Object); // true
基于程序中某个输入、条件或结果的具体问题
在自定义构造函数或使用原型链模拟继承时,instanceof 的行为可能因原型链的修改而改变。例如,如果手动修改了构造函数的 prototype,instanceof 的结果也会随之变化。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











