常见数据类型的原型链指向
obj -> Object.prototype -> nullfunc -> Function.prototype -> Object.prototype -> nullarr -> Array.prototype -> Object.prototype -> null
- obj是Object实例
- func是Function实例,也是Object实例
- arr是Array实例,也是Object实例
关于原型链的基本原则
-
若A沿着原型链能找到B.prototype, 则A instanceof B为true
-
如果在A对象上没有找到x属性,那么会沿着原型链找x属性
const obj = {}; obj instanceof Object; // trueconst func = () => {}; func instanceof Function; // true func instanceof Object; // trueconst arr = []; arr instanceof Array; // true arr instanceof Object; // true
原型链的查找顺序
1 )相同类型查找
const obj = {};
Object.prototype.x = 'x';
console.log(obj.x); // xconst func = () => {}
Function.prototype.y = 'y';
console.log(func.y); // yconst arr = [];
Array.prototype.z = 'z';
console.log(arr.z); // z
2 )不同类型查找, 交叉验证
const obj = {};
const func = () => {};Object.prototype.a = 'aaa';
Function.prototype.b = 'bbb';// 验证
console.log(obj.a); // aaa
console.log(obj.b); // undefinedconsole.log(func.a); // aaa
console.log(func.b); // bbb
算法实现原型链的查找规则
const instanceOf = (A, B) => {let p = A; // 将指针先指向A// 使用指针遍历原型链while(p) {// 判断当前是否符合预期if (p === B.prototype) {return true;}p = p.__proto__; // 向上查找}return false;
}