解释instanceof
instanceof检查左侧的__proto__是否等于右侧的prototype
function Animal() {}
Animal.prototype.eat = function() { console.log("Eating...") };function Dog() {}
Dog.prototype = new Animal(); // Dog 继承 Animal
Dog.prototype.bark = function() { console.log("Bark!") };const myDog = new Dog();
因为
console.log(myDog.__proto__=== Dog.prototype);//true
console.log(myDog.__proto__.__proto__=== Animal.prototype);//true
所以
console.log(myDog instanceof Dog)//true
console.log(myDog instanceof Animal)//true
无论经过几层的__proto__,只要能找到prototype就是true
如果修改了prototype,会影响结果
function Parent() {}
function Child() {}
Child.prototype = Object.create(Parent.prototype);const child = new Child();
console.log(child instanceof Child); // true
console.log(child instanceof Parent); // true(因Parent.prototype在原型链中)// 动态修改prototype的影响
function Foo() {}
const obj = new Foo();
console.log(obj instanceof Foo); // true
Foo.prototype = {}; // 修改prototype
console.log(obj instanceof Foo); // false(obj的原型链未更新)
手动实现instanceof
function myInstanceOf(obj, Constructor) {if (typeof obj !== 'object' || obj === null) return false;let proto = Object.getPrototypeOf(obj);while (proto !== null) {if (proto === Constructor.prototype) return true;proto = Object.getPrototypeOf(proto);}return false;
}