链表是什么
- 多个元素组成的列表
- 元素存储不连续,用next指针连在一起
数组 vs 链表
数组:增删非首尾元素时往往需要移动元素。
链表:增删非首尾元素,不需要移动元素,只需要更改next指针
JS中的链表
JavaScript 中没有链表
可以用Object模拟链表
const a = { val: 'a' };
const b = { val: 'b' };
const c = { val: 'c' };
const d = { val: 'd' };
a.next = b;
b.next = c;
c.next = d;
// 插入
const e = { val: 'e'};
c.next = e;
e.next = d;
// 删除
// c.next = d;
// 遍历链表
let p = a;
while(p) {
console.log(p.val);
p = p.next;
}
原型链
- 原型链的本质是链表
- 原型链上的节点是各种原型对象,比如Function.prototype、Object.prototype
- 原型链通过__proto__属性连接各种原型
obj -> Object.prototype -> null
func- > Function.prototype -> Object.prototype -> null
arr -> Array.prototype -> Object.prototype -> null
知识点:
如果A沿着原型链能找到B.prototype,那么A instanceof B 为true
如果在A对象上没有找到x属性,那么会沿着原型链找x属性
面试题一
简述instance的原理
知识点:
如果A沿着原型链能找到B.prototype,那么A instanceof B 为true
解法:
遍历A的原型链,如果找到B.prototype,返回true,否则返回false
const instanceOf = (A, B) => {
let p = A;
while (p) {
if(p === B.prototype) {
return true
}
p = p.__proto__
}
return false
}
console.log(instanceOf(1, Number));
面试题二
知识点:
如果在A对象上没有找到x属性,那么会沿着原型链找x属性
解法:
明确foo和F变量的原型链,沿着原型链找a属性和b属性
var foo = {}
F = function () {}
Object.prototype.a = 'value a'
Function.prototype.b = 'value b'
console.log(foo.a); // value a
console.log(foo.b); // undefined
console.log(F.a); // value a
console.log(F.b); // value b