前端面试八股文:JavaScript 原型链

前端面试八股文:JavaScript 原型链

一、前言:为什么原型链如此重要?

在 JavaScript 的世界里,原型链是一个"既熟悉又陌生"的概念。很多开发者知道它的存在,却很少直接操作它。然而,原型链是 JavaScript 面向对象编程的基石,理解它不仅能帮助你通过面试,更能让你深入理解 JavaScript 的设计哲学。

二、核心概念:什么是原型链?

1. 基本定义

原型链是 JavaScript 中实现继承和共享属性的机制。每个对象都有一个内部链接指向它的原型(通过 __proto__[[Prototype]]),当访问对象的属性时,如果对象自身没有该属性,就会沿着原型链向上查找,直到找到属性或到达链的末端(null)。

2. 关键术语澄清

// 混淆点澄清functionPerson(){}const p =newPerson();// 易混淆的三个概念: console.log(p.__proto__);// Person.prototype console.log(Person.prototype);// 构造函数的原型对象 console.log(Person.__proto__);// Function.prototype// 正确的关系:// p.__proto__ === Person.prototype// Person.prototype.__proto__ === Object.prototype// Object.prototype.__proto__ === null

3. 原型链的"终点站"

任意对象 → Object.prototype → null ↑ └── 原型链查找的终点 

三、原型链的工作原理

1. 属性查找过程

const obj ={name:'小明'};// 查找 obj.toString() 的过程:// 1. 检查 obj 自身是否有 toString 属性 ❌// 2. 检查 obj.__proto__ (Object.prototype) ✅ 找到!// 3. 调用 Object.prototype.toString()

2. 完整的继承体系

functionAnimal(name){this.name = name;}Animal.prototype.eat=function(){ console.log(`${this.name}正在吃`);};functionDog(name, breed){Animal.call(this, name);// 继承属性this.breed = breed;}// 设置原型链Dog.prototype = Object.create(Animal.prototype);Dog.prototype.constructor = Dog;Dog.prototype.bark=function(){ console.log(`${this.name}在叫:汪汪!`);};const myDog =newDog('旺财','柯基');// 原型链结构:// myDog → Dog.prototype → Animal.prototype → Object.prototype → null

四、现代 JavaScript 中的原型链

1. ES6 Class 是语法糖

// ES6 Class 写法classPerson{constructor(name){this.name = name;}sayHello(){ console.log(`Hello, ${this.name}`);}}// 等价于 ES5 写法functionPerson(name){this.name = name;}Person.prototype.sayHello=function(){ console.log(`Hello, ${this.name}`);};// 验证const p1 =newPerson('Alice'); console.log(p1.sayHello ===Person.prototype.sayHello);// true

2. 继承的实现

// ES6classAnimal{constructor(name){this.name = name;}}classDogextendsAnimal{constructor(name, breed){super(name);this.breed = breed;}}// Babel 编译后的 ES5 代码function_inherits(subClass, superClass){ subClass.prototype = Object.create( superClass && superClass.prototype,{constructor:{value: subClass }});if(superClass){ Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass): subClass.__proto__ = superClass;}}

五、原型链在实际开发中的应用

应用1:框架中的原型扩展

// Vue 2 的实例方法Vue.prototype.$nextTick=function(fn){returnnextTick(fn,this);};Vue.prototype.$set = set;Vue.prototype.$delete= del;// 使用exportdefault{mounted(){this.$nextTick(()=>{// DOM 更新后执行});}};

应用2:工具库的实现

// Lodash 风格的工具函数function_(){if(!(thisinstanceof_))returnnew_(...arguments);this.__wrapped__ = arguments[0];}// 链式调用支持_.prototype.chain=function(){this.__chain__ =true;returnthis;};// 取值_.prototype.value=function(){returnthis.__wrapped__;};

应用3:Polyfill 实现

// Array.prototype.includes 的 Polyfillif(!Array.prototype.includes){ Object.defineProperty(Array.prototype,'includes',{value:function(searchElement, fromIndex){// 实现逻辑...},writable:true,configurable:true});}

六、性能优化:为什么原型链重要?

1. 内存优化对比

// ❌ 方法定义在构造函数内(浪费内存)functionPerson(name){this.name = name;this.sayHello=function(){ console.log(`Hello, ${this.name}`);};}// 创建1000个实例const people1 =[];for(let i =0; i <1000; i++){ people1.push(newPerson(`Person${i}`));}// 内存中有1000个sayHello函数// ✅ 方法定义在原型上(节省内存)functionBetterPerson(name){this.name = name;}BetterPerson.prototype.sayHello=function(){ console.log(`Hello, ${this.name}`);};// 创建1000个实例const people2 =[];for(let i =0; i <1000; i++){ people2.push(newBetterPerson(`Person${i}`));}// 内存中只有1个sayHello函数

2. 属性查找性能

// 原型链查找 vs 闭包classWithPrototype{calculate(){returnthis.x +this.y;}}classWithClosure{constructor(x, y){this.calculate=()=> x + y;}}// 性能测试:原型方法通常更快,因为共享代码

七、面试常见问题与回答

Q1:new 操作符做了什么?

A:

functionmyNew(Constructor,...args){// 1. 创建空对象,链接原型const obj = Object.create(Constructor.prototype);// 2. 绑定 this 并执行构造函数const result =Constructor.apply(obj, args);// 3. 返回对象(如果构造函数返回对象则使用它)return result instanceofObject? result : obj;}

Q2:如何实现继承?

A:

// 最佳实践:组合继承 + 寄生组合继承functionParent(name){this.name = name;}Parent.prototype.sayName=function(){ console.log(this.name);};functionChild(name, age){Parent.call(this, name);// 继承实例属性this.age = age;}// 继承原型方法(寄生组合式)Child.prototype = Object.create(Parent.prototype);Child.prototype.constructor = Child;// 添加子类方法Child.prototype.sayAge=function(){ console.log(this.age);};

Q3:Object.create 和 new 的区别?

A:

// Object.create:创建新对象,指定原型const proto ={x:10};const obj1 = Object.create(proto);// obj1.__proto__ === proto// new:创建新对象,执行构造函数functionF(){}const obj2 =newF();// obj2.__proto__ === F.prototype// Object.create(null) 创建无原型的"纯净"对象const pureObj = Object.create(null); console.log(pureObj.toString);// undefined

Q4:ES6 Class 和 ES5 原型的区别?

A:

  1. 语法糖:Class 是更清晰的语法,底层仍是原型
  2. 继承实现extends 自动处理原型链
  3. 静态方法:Class 有明确的 static 语法
  4. 私有字段:ES2022 支持真正的私有字段 #field
  5. super 关键字:更优雅地调用父类方法

八、最佳实践与注意事项

✅ 推荐做法

// 1. 使用 Class 语法classUser{constructor(name){this.name = name;}// 方法自动进入原型sayHello(){return`Hello, ${this.name}`;}// 静态方法staticcreateAdmin(){returnnewUser('admin');}}// 2. 避免污染内置原型// ❌ 不推荐// Array.prototype.myMethod = function() { ... };// ✅ 推荐classMyArrayextendsArray{myMethod(){// 自定义方法}}// 3. 使用组合优于复杂继承const canEat ={eat(){ console.log(`${this.name} is eating`);}};const canSleep ={sleep(){ console.log(`${this.name} is sleeping`);}};classAnimal{constructor(name){this.name = name;}}// 混入 Object.assign(Animal.prototype, canEat, canSleep);

⚠️ 注意事项

  1. 原型链不宜过深(通常不超过3层)
  2. 避免修改 __proto__(使用 Object.setPrototypeOf
  3. 注意性能:深层原型链查找会影响性能
  4. 使用 Object.hasOwnProperty 区分自身属性和继承属性

九、总结:原型链的现代意义

原型链不是过时的概念,而是 JavaScript 核心特性。虽然现代开发中直接操作原型链的场景减少,但理解原型链能帮你:

  1. 深入理解框架:Vue/React 等框架底层都依赖原型
  2. 编写高效代码:合理使用原型节省内存
  3. 调试更顺畅:知道属性/方法的来源
  4. 通过面试:这是必考的基础知识
  5. 学习新特性:理解 ES6+ 特性的底层实现

记住:你每天写的 array.map()class extendsthis.$router 都在使用原型链。它不是你需要"使用"的工具,而是你需要"理解"的基石。

掌握原型链,你就掌握了 JavaScript 面向对象编程的核心。

Read more

C++ 智能指针完全指南:原理、用法与避坑实战(从 RAII 到循环引用)

C++ 智能指针完全指南:原理、用法与避坑实战(从 RAII 到循环引用)

🔥草莓熊Lotso:个人主页 ❄️个人专栏: 《C++知识分享》《Linux 入门到实践:零基础也能懂》 ✨生活是默默的坚持,毅力是永久的享受! 🎬 博主简介: 文章目录 * 前言: * 一. 智能指针的核心:RAII 设计思想 * 1.1 为什么需要智能指针? * 1.2 RAII:智能指针的设计灵魂 * 二. C++ 标准库智能指针:用法与场景 * 2.1 unique_ptr:独占式智能指针(推荐优先使用) * 2.2 shared_ptr:共享式智能指针(支持拷贝,重点了解) * 2.3 weak_ptr:弱引用智能指针(解决循环引用) * 2.3.1

By Ne0inhk
【C++初阶】C++入门相关知识(2):输入输出 & 缺省参数 & 函数重载

【C++初阶】C++入门相关知识(2):输入输出 & 缺省参数 & 函数重载

🎈主页传送门:良木生香 🔥个人专栏:《C语言》 《数据结构-初阶》 《程序设计》《鼠鼠的C++学习之路》 🌟人为善,福随未至,祸已远行;人为恶,祸虽未至,福已远离 上期回顾:在上一篇文章中,我们对C++进行了初步的认识,学习了C++的发展历史,第一个C++程序以及命名空间,我们知道,C++的出现就是为了改进和完善C语言的不足,使得程序更加高效,程序员编写起来更加方便快捷,那么本篇文章我们继续往下认识C++的入门相关知识 目录 一、C++的输入&输出 1.1、核心载体:头文件 1.2、核心的IO对象:cin与cout 1.2.1、std::cin 标准输入流 1.

By Ne0inhk
C++进阶:(十六)从裸指针到智能指针,C++ 内存管理的 “自动驾驶” 进化之路

C++进阶:(十六)从裸指针到智能指针,C++ 内存管理的 “自动驾驶” 进化之路

目录 前言 一、裸指针的 “血泪史”:为什么我们需要智能指针? 1.1 内存泄漏:最常见的 “噩梦” 1.2 二次释放:致命的 “双重打击” 1.3 野指针:潜伏的 “幽灵” 1.4 异常安全:被忽略的 “隐形杀手” 1.5 智能指针的核心使命 二、智能指针的 “三驾马车”:unique_ptr、shared_ptr、weak_ptr 2.1 unique_ptr:独占所有权的 “独行侠” 2.1.1 unique_ptr 的核心原理

By Ne0inhk
C++之《程序员自我修养》读书总结(5)

C++之《程序员自我修养》读书总结(5)

《程序员自我修养》读书总结(五) Author: Once Day Date: 2026年2月12日 一位热衷于Linux学习和开发的菜鸟,试图谱写一场冒险之旅,也许终点只是一场白日梦… 漫漫长路,有人对你微笑过嘛… 全系列文章可参考专栏: 书籍阅读_Once-Day的博客-ZEEKLOG博客 参考文章:《程序员的自我修养》读书笔记 | Zachary’s blog《程序员的自我修养》阅读笔记 - T0fV404 - 博客园读书笔记:《程序员的自我修养》 - 楷哥 - 博客园 文章目录 * 《程序员自我修养》读书总结(五) * 5. Windows PE/COFF 格式 * 5.1 发展历史 * 5.2 mingw-w64 工具链 * 5.

By Ne0inhk