关于 instanceof 的用法,我的一篇文章讲解到了,欢迎大家去看看instanceof
下面贴出我手写的instanceof
function _instanceof(ex, Fn) {
while (ex.__proto__) {
if (ex.__proto__ === Fn.prototype) {
return true;
};
ex = ex.__proto__;
};
return false;
};
结合三个例子
function Son() {};
let son = new Son();
console.log(_instanceof(son, Son)); // true son.__proto__ === Son.prototype的,也就是son是 Son的实例
function Father() {};
function Son() {};
Son.prototype = Object.create(Father.prototype); // Son.prototype.__proto__ = Father.prototype
let son = new Son();
console.log(_instanceof(son, Father)); // true son.__proto__ === Son.prototype, son 不是father的直接实例,继续遍历,发现 Son.prototype.__proto__ === Father.prototype, 返回true
function Son() {};
let son = new Son();
console.log(_instanceof(son, Object)); // true, 所有对象原型链的顶端都是Object.prototype,也就是 Son.prototype.__proto__ === Object.prototype(注意这是非继承下。继承下 Son.prototype.__proto___ === Father.prototype, Father.prototype.__proto__ === Object.prototype)