原型与原型链
原型链是 JS 继承的机制:每个对象有 __proto__ 指向其构造函数的 prototype,访问属性时沿这条链向上查找,直到 Object.prototype(再上是 null)。Function 比较特殊:所有函数的 __proto__ 都指向 Function.prototype,而后者本身是个函数对象。
一张图记住核心关系:构造函数 Foo 有 prototype(含 constructor 指回 Foo);实例 f.__proto__ === Foo.prototype;Foo.prototype.__proto__ === Object.prototype。手写 new 是这题的标配追问:创建空对象、链接原型、绑定 this 执行、返回对象类型结果。
- 访问属性沿 __proto__ 链向上找,终点是 Object.prototype → null
- 实例.__proto__ === 构造函数.prototype;prototype.constructor 指回构造函数
- 手写 new 四步:建对象、链原型、绑 this、返对象
JS
function Foo(name) { this.name = name; } Foo.prototype.say = function () { return '我是 ' + this.name; }; const f = new Foo('小明'); console.log(f.say()); // 我是小明(沿原型链找到) console.log(f.__proto__ === Foo.prototype); // true console.log(Foo.prototype.constructor === Foo); // true console.log(Foo.prototype.__proto__ === Object.prototype); // true console.log(Object.prototype.__proto__); // null(链的终点) // 手写 new(面试高频) function myNew(Ctor, ...args) { const obj = Object.create(Ctor.prototype); // 1+2 建对象并链接原型 const res = Ctor.apply(obj, args); // 3 绑定 this 执行 return res instanceof Object ? res : obj; // 4 构造函数返回对象则用它 } const f2 = myNew(Foo, '小红'); console.log(f2.say()); // 我是小红 // ES5 继承范式:组合继承(了解原理即可,class 已取代) function Bar(name, age) { Foo.call(this, name); this.age = age; } Bar.prototype = Object.create(Foo.prototype); Bar.prototype.constructor = Bar;
本节要点原型链 = 属性查找的路径:实例 → 构造函数.prototype → Object.prototype → null;手写 new 四步必会。




