常见数据类型的原型链指向
obj -> Object.prototype -> null
func -> Function.prototype -> Object.prototype -> null
arr -> 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; // true const func = () => {}; func instanceof Function; // true func instanceof Object; // true const arr = []; arr instanceof Array; // true arr instanceof Object; // true
原型链的查找顺序
1 )相同类型查找
const obj = {};
Object.prototype.x = 'x';
console.log(obj.x); // x
const func = () => {}
Function.prototype.y = 'y';
console.log(func.y); // y
const 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); // undefined
console.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;
}
442



被折叠的 条评论
为什么被折叠?



