解释一下原型、构造函数、实例、原型链 之间的关系?
参考答案
- 构造函数:普通函数,用
new创建实例,拥有prototype属性; - 原型对象:即
Ctor.prototype,存放共享方法与属性,自带constructor指回构造函数; - 实例:
new出来的对象,内部[[Prototype]](__proto__)指向Ctor.prototype; - 原型链:实例 → 构造函数 prototype → 上一层 prototype → … →
Object.prototype→null。
function A() {}
const a = new A();
a.__proto__ === A.prototype; // true
A.prototype.constructor === A; // true
Object.prototype.__proto__ === null; // 终点
属性查找沿原型链向上,直到找到或到 null 为止。