前端面试500题大全

前端开发面试 500 题大全(含答案、解析和示例)
本文收集了前端开发工程师最常见的 500 道面试题,涵盖了前端开发的各个方面,包括但不限于 HTML5、CSS3、JavaScript、ES6+、Vue、React、浏览器原理、网络协议、前端工程化等领域。每道题都配有详细的答案解析和实际示例,帮助你更好地理解和掌握相关知识点。
目录
HTML5 CSS3
1. 什么是语义化标签?请列举常用的语义化标签并说明其用途。
答案解析:
语义化标签是指使用恰当的 HTML 标签来传达文档结构和内容的含义,而不是单纯为了展示效果。使用语义化标签有以下好处:
提高代码可读性和可维护性
有利于 SEO 优化
提升无障碍访问体验
便于不同设备解析页面结构
常用的语义化标签包括:
  1. <header> - 页面或区块的头部
  2. <nav> - 导航栏
  3. <main> - 主要内容
  4. <article> - 独立的文章内容
  5. <section> - 区块
  6. <aside> - 侧边栏
  7. <footer> - 页面或区块的底部
  8. <figure> - 图片或图表
  9. <figcaption> - 图片或图表的说明
html
示例:
  1. <header>
  2. <nav>
  3. <ul>
  4. <li><a href="#home">首页</a>li>
  5. <li><a href="#about">关于</a>li>
  6. ul>
  7. nav>
  8. header>

  9. <main>
  10. <article>
  11. <h1>文章标题h1>
  12. <section>
  13. <h2>第一章h2>
  14. <p>章节内容...p>
  15. section>
  16. article>
  17. <aside>
  18. <h3>相关文章h3>
  19. <ul>
  20. <li><a href="#">推荐阅读 1</a>li>
  21. <li><a href="#">推荐阅读 2</a>li>
  22. ul>
  23. aside>
  24. main>

  25. <footer>
  26. <p>版权所有 © 2024p>
  27. footer>
html
2. 请详细解释 CSS 盒模型,以及标准盒模型和 IE 盒模型的区别。
答案解析:
CSS 盒模型描述了网页中的元素如何显示以及如何计算它们的尺寸。每个元素都被表示为一个矩形盒子,包含以下部分:
content(内容)
padding(内边距)
border(边框)
margin(外边距)
标准盒模型和 IE 盒模型的主要区别在于宽度和高度的计算方式:
标准盒模型(content-box):width/height 只包含 content
IE 盒模型(border-box):width/height 包含 content + padding + border
示例:
  1. /* 标准盒模型 */
  2. .standard-box {
  3. box-sizing: content-box; /* 默认值 */
  4. width: 200px;
  5. padding: 20px;
  6. border: 1px solid #000;
  7. /* 实际宽度 = 200px + 40px(padding) + 2px(border) = 242px */
  8. }

  9. /* IE盒模型 */
  10. .ie-box {
  11. box-sizing: border-box;
  12. width: 200px;
  13. padding: 20px;
  14. border: 1px solid #000;
  15. /* 实际宽度 = 200px(包含padding和border) */
  16. }
css
在实际开发中,通常推荐使用 IE 盒模型(border-box),因为它更直观且便于计算。常见的全局设置:
  1. * {
  2. box-sizing: border-box;
  3. }
css
3. 请解释 CSS 中的 BFC(Block Formatting Context)及其应用场景。
答案解析:
BFC(Block Formatting Context)是 CSS 中的一个重要概念,它是一个独立的渲染区域,有自己的渲染规则:
内部的盒子会在垂直方向上一个接一个放置
同一个 BFC 内的相邻元素的 margin 会发生重叠
BFC 区域不会与浮动元素重叠
BFC 能包含浮动元素(清除浮动)
BFC 就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素
触发 BFC 的条件:
根元素(<html>
浮动元素(float 不为 none)
绝对定位元素(position absolute fixed)
display inline-block、flex、grid、flow-root
overflow 不为 visible 的块级元素
应用场景示例:
清除浮动:
  1. <style>
  2. .container {
  3. overflow: hidden; /* 触发 BFC */
  4. }
  5. .float-item {
  6. float: left;
  7. width: 100px;
  8. height: 100px;
  9. background: #f0f0f0;
  10. }
  11. style>

  12. <div class="container">
  13. <div class="float-item">div>
  14. <div class="float-item">div>
  15. div>
html
防止 margin 重叠:
  1. <style>
  2. .box {
  3. margin: 20px 0;
  4. background: #f0f0f0;
  5. }
  6. .bfc-container {
  7. display: flow-root; /* 触发 BFC */
  8. }
  9. style>

  10. <div class="box">Box 1div>
  11. <div class="bfc-container">
  12. <div class="box">Box 2div>
  13. div>
html
自适应两栏布局:
  1. <style>
  2. .aside {
  3. float: left;
  4. width: 200px;
  5. background: #f0f0f0;
  6. }
  7. .main {
  8. display: flow-root; /* 触发 BFC */
  9. background: #ddd;
  10. }
  11. style>

  12. <div class="aside">侧边栏div>
  13. <div class="main">主要内容div>
html
4. 请详细解释 CSS Flexbox 布局模型及其常用属性。
答案解析:
Flexbox(弹性盒子)是一种一维布局模型,它提供了强大的空间分布和对齐能力。主要包含两个角色:容器(flex container)和项目(flex item)。
Flex 容器属性:
display: flex | inline-flex:定义 flex 容器
flex-direction:主轴方向
flex-wrap:是否换行
justify-content:主轴对齐方式
align-items:交叉轴对齐方式
align-content:多行对齐方式
Flex 项目属性:
flex-grow:放大比例
flex-shrink:缩小比例
flex-basis:基准大小
flex:上述三个属性的简写
align-self:单个项目对齐方式
order:排列顺序
示例:
  1. <style>
  2. .container {
  3. display: flex;
  4. justify-content: space-between;
  5. align-items: center;
  6. height: 200px;
  7. background: #f0f0f0;
  8. }

  9. .item {
  10. flex: 1;
  11. height: 100px;
  12. margin: 0 10px;
  13. background: #ddd;
  14. }

  15. .item:nth-child(2) {
  16. flex: 2; /* 占据2倍空间 */
  17. }
  18. style>

  19. <div class="container">
  20. <div class="item">1div>
  21. <div class="item">2div>
  22. <div class="item">3div>
  23. div>
html
常见布局场景:
居中布局:
  1. .center {
  2. display: flex;
  3. justify-content: center;
  4. align-items: center;
  5. }
css
等分布局:
  1. .equal {
  2. display: flex;
  3. }
  4. .equal > * {
  5. flex: 1;
  6. }
css
粘性页脚:
  1. .page {
  2. display: flex;
  3. flex-direction: column;
  4. min-height: 100vh;
  5. }
  6. .content {
  7. flex: 1;
  8. }
css
5. 请解释 CSS Grid 布局系统及其与 Flexbox 的区别。
答案解析:
CSS Grid 是一个二维布局系统,专门用于创建基于网格的布局。与 Flexbox 的一维布局不同,Grid 可以同时控制行和列的布局。
Grid 容器属性:
display: grid | inline-grid:定义网格容器
grid-template-columns:定义列的大小和数量
grid-template-rows:定义行的大小和数量
grid-gap:定义网格间距
grid-template-areas:定义网格区域
Grid 项目属性:
grid-column:指定列的开始和结束位置
grid-row:指定行的开始和结束位置
grid-area:指定项目所在的区域
示例:
  1. <style>
  2. .grid-container {
  3. display: grid;
  4. grid-template-columns: repeat(3, 1fr);
  5. grid-template-rows: auto 1fr auto;
  6. grid-gap: 20px;
  7. height: 100vh;
  8. }

  9. .header {
  10. grid-column: 1 / -1; /* 跨越所有列 */
  11. background: #f0f0f0;
  12. }

  13. .sidebar {
  14. grid-row: 2 / 3;
  15. background: #ddd;
  16. }

  17. .main {
  18. grid-column: 2 / -1;
  19. grid-row: 2 / 3;
  20. background: #ccc;
  21. }

  22. .footer {
  23. grid-column: 1 / -1;
  24. background: #f0f0f0;
  25. }
  26. style>

  27. <div class="grid-container">
  28. <header class="header">页头header>
  29. <aside class="sidebar">侧边栏aside>
  30. <main class="main">主要内容main>
  31. <footer class="footer">页脚footer>
  32. div>
html
Grid vs Flexbox:
维度:
Grid:二维布局(行和列)
Flexbox:一维布局(主轴)
适用场景:
Grid:适合整体页面布局
Flexbox:适合组件内部布局
方向控制:
Grid:可以同时控制两个方向
Flexbox:主要控制一个方向
对齐方式:
Grid:更适合大规模的网格系统
Flexbox:更适合小规模的灵活布局
6. 解释 CSS 中的定位(position)属性及其应用场景。
答案解析:
CSS 定位属性用于控制元素在页面中的位置,包括以下值:
static(默认值)
relative(相对定位)
absolute(绝对定位)
fixed(固定定位)
sticky(粘性定位)
各种定位的特点和应用:
relative
相对于自身原始位置偏移
不脱离文档流
常用于为绝对定位子元素提供参考点
  1. .relative-box {
  2. position: relative;
  3. top: 20px;
  4. left: 20px;
  5. }
css
absolute
相对于最近的非 static 定位祖先元素定位
脱离文档流
常用于弹窗、工具提示等
  1. .modal {
  2. position: absolute;
  3. top: 50%;
  4. left: 50%;
  5. transform: translate(-50%, -50%);
  6. }
css
fixed
相对于视口定位
脱离文档流
常用于固定导航栏、返回顶部按钮等
  1. .navbar {
  2. position: fixed;
  3. top: 0;
  4. left: 0;
  5. width: 100%;
  6. }
css
sticky
在阈值之前为相对定位,之后为固定定位
不脱离文档流
常用于吸顶导航、表格头等
  1. .sticky-header {
  2. position: sticky;
  3. top: 0;
  4. background: white;
  5. z-index: 1;
  6. }
css
实际应用示例:
固定导航栏:
  1. <style>
  2. .navbar {
  3. position: fixed;
  4. top: 0;
  5. left: 0;
  6. width: 100%;
  7. background: white;
  8. box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  9. z-index: 1000;
  10. }
  11. style>
html
模态框居中:
  1. <style>
  2. .modal-overlay {
  3. position: fixed;
  4. top: 0;
  5. left: 0;
  6. width: 100%;
  7. height: 100%;
  8. background: rgba(0,0,0,0.5);
  9. }

  10. .modal {
  11. position: absolute;
  12. top: 50%;
  13. left: 50%;
  14. transform: translate(-50%, -50%);
  15. background: white;
  16. padding: 20px;
  17. border-radius: 4px;
  18. }
  19. style>
html
吸顶效果:
  1. <style>
  2. .section-header {
  3. position: sticky;
  4. top: 0;
  5. padding: 10px;
  6. background: white;
  7. border-bottom: 1px solid #eee;
  8. }
  9. style>
html
7. CSS 预处理器(如 Sass/Less)的主要特性和优势是什么?
答案解析:
CSS 预处理器是一种专门的编程语言,让 CSS 具备了一定的编程能力,增强了 CSS 的可维护性和复用性。
主要特性:
变量:
  1. // SCSS
  2. $primary-color: #3498db;
  3. $spacing: 20px;

  4. .button {
  5. background: $primary-color;
  6. padding: $spacing;
  7. }
scss
嵌套:
  1. .nav {
  2. background: #fff;
  3. &__item { // 编译为 .nav__item
  4. padding: 10px;
  5. &:hover { // 编译为 .nav__item:hover
  6. background: #f0f0f0;
  7. }
  8. }
  9. }
scss
混合(Mixins):
  1. @mixin flex-center {
  2. display: flex;
  3. justify-content: center;
  4. align-items: center;
  5. }

  6. .card {
  7. @include flex-center;
  8. background: #fff;
  9. }
scss
函数:
  1. @function calculate-width($n) {
  2. @return $n * 100px;
  3. }

  4. .container {
  5. width: calculate-width(3); // 300px
  6. }
scss
继承:
  1. %button-base {
  2. padding: 10px 20px;
  3. border: none;
  4. border-radius: 4px;
  5. }

  6. .button-primary {
  7. @extend %button-base;
  8. background: blue;
  9. }

  10. .button-secondary {
  11. @extend %button-base;
  12. background: gray;
  13. }
scss
主要优势:
代码复用性:
通过变量、混合、继承减少重复代码
可以创建可复用的样式库
可维护性:
更好的代码组织
模块化开发
命名空间
开发效率:
嵌套减少重复选择器
运算能力
自动化工具集成
逻辑处理:
条件语句
循环
函数
示例:完整的 SCSS 应用
  1. // 变量
  2. $primary: #3498db;
  3. $secondary: #2ecc71;
  4. $spacing: 20px;

  5. // 混合
  6. @mixin button($bg-color) {
  7. padding: $spacing / 2;
  8. background: $bg-color;
  9. border: none;
  10. border-radius: 4px;
  11. &:hover {
  12. background: darken($bg-color, 10%);
  13. }
  14. }

  15. // 函数
  16. @function strip-unit($value) {
  17. @return $value / ($value * 0 + 1);
  18. }

  19. // 基础样式
  20. %flex-center {
  21. display: flex;
  22. justify-content: center;
  23. align-items: center;
  24. }

  25. // 组件样式
  26. .container {
  27. @extend %flex-center;
  28. max-width: 1200px;
  29. margin: 0 auto;
  30. padding: $spacing;
  31. .content {
  32. flex: 1;
  33. @media (max-width: 768px) {
  34. padding: $spacing / 2;
  35. }
  36. }
  37. }

  38. .button {
  39. &--primary {
  40. @include button($primary);
  41. }
  42. &--secondary {
  43. @include button($secondary);
  44. }
  45. }
scss
编译后的 CSS:
  1. .container {
  2. display: flex;
  3. justify-content: center;
  4. align-items: center;
  5. max-width: 1200px;
  6. margin: 0 auto;
  7. padding: 20px;
  8. }

  9. .container .content {
  10. flex: 1;
  11. }

  12. @media (max-width: 768px) {
  13. .container .content {
  14. padding: 10px;
  15. }
  16. }

  17. .button--primary {
  18. padding: 10px;
  19. background: #3498db;
  20. border: none;
  21. border-radius: 4px;
  22. }

  23. .button--primary:hover {
  24. background: #217dbb;
  25. }

  26. .button--secondary {
  27. padding: 10px;
  28. background: #2ecc71;
  29. border: none;
  30. border-radius: 4px;
  31. }

  32. .button--secondary:hover {
  33. background: #25a25a;
  34. }
css
8. 请详细解释 CSS3 中的转换(Transform)、过渡(Transition)和动画(Animation)。
答案解析:
CSS3 提供了强大的动画和过渡效果能力,主要包括三个方面:转换、过渡和动画。
1. 转换(Transform)
transform 属性允许你旋转、缩放、倾斜或平移给定元素:
  1. .transform-example {
  2. /* 2D 转换 */
  3. transform: translate(50px, 100px) /* 平移 */
  4. rotate(45deg) /* 旋转 */
  5. scale(1.5) /* 缩放 */
  6. skew(10deg, 20deg); /* 倾斜 */
  7. /* 3D 转换 */
  8. transform: rotateX(45deg) /* 3D 旋转 */
  9. perspective(1000px) /* 透视 */
  10. translateZ(100px); /* Z轴平移 */
  11. }
css
2. 过渡(Transition)
transition 允许在一定时间内平滑地改变属性值:
  1. .transition-example {
  2. width: 100px;
  3. background: blue;
  4. transition: all 0.3s ease-in-out;
  5. }

  6. .transition-example:hover {
  7. width: 200px;
  8. background: red;
  9. }
css
过渡属性包括:
transition-property:要过渡的属性
transition-duration:过渡持续时间
transition-timing-function:过渡时间函数
transition-delay:过渡延迟时间
3. 动画(Animation)
animation 允许创建复杂的自定义动画:
  1. /* 定义关键帧 */
  2. @keyframes slide-in {
  3. 0% {
  4. transform: translateX(-100%);
  5. opacity: 0;
  6. }
  7. 100% {
  8. transform: translateX(0);
  9. opacity: 1;
  10. }
  11. }

  12. .animation-example {
  13. animation: slide-in 1s ease-out forwards;
  14. }

  15. /* 多个动画组合 */
  16. .multiple-animations {
  17. animation:
  18. slide-in 1s ease-out,
  19. fade-in 2s ease-in;
  20. }
css
动画属性包括:
animation-name:动画名称
animation-duration:动画持续时间
animation-timing-function:动画时间函数
animation-delay:动画延迟时间
animation-iteration-count:动画重复次数
animation-direction:动画方向
animation-fill-mode:动画填充模式
animation-play-state:动画播放状态
实际应用示例:
按钮悬停效果:
  1. .button {
  2. padding: 10px 20px;
  3. background: #3498db;
  4. color: white;
  5. border: none;
  6. border-radius: 4px;
  7. transition: all 0.3s ease;
  8. }

  9. .button:hover {
  10. transform: translateY(-2px);
  11. box-shadow: 0 5px 15px rgba(0,0,0,0.2);
  12. }
css
加载动画:
  1. @keyframes spin {
  2. 0% { transform: rotate(0deg); }
  3. 100% { transform: rotate(360deg); }
  4. }

  5. .loader {
  6. width: 40px;
  7. height: 40px;
  8. border: 4px solid #f3f3f3;
  9. border-top: 4px solid #3498db;
  10. border-radius: 50%;
  11. animation: spin 1s linear infinite;
  12. }
css
卡片翻转效果:
  1. .card {
  2. position: relative;
  3. width: 300px;
  4. height: 200px;
  5. transform-style: preserve-3d;
  6. transition: transform 0.6s;
  7. }

  8. .card:hover {
  9. transform: rotateY(180deg);
  10. }

  11. .card-front,
  12. .card-back {
  13. position: absolute;
  14. width: 100%;
  15. height: 100%;
  16. backface-visibility: hidden;
  17. }

  18. .card-back {
  19. transform: rotateY(180deg);
  20. }
css
9. 解释 CSS3 中的响应式设计和媒体查询。
答案解析:
响应式设计是一种让网站能够自适应不同设备和屏幕尺寸的设计方法。主要通过媒体查询(Media Queries)和弹性布局来实现。
1. 媒体查询基础语法:
  1. @media screen and (max-width: 768px) {
  2. /* 针对屏幕宽度小于等于 768px 的样式 */
  3. }

  4. @media screen and (min-width: 769px) and (max-width: 1024px) {
  5. /* 针对屏幕宽度在 769px 到 1024px 之间的样式 */
  6. }
css
2. 常见断点设置:
  1. /* 移动优先的响应式设计 */
  2. /* 基础样式(移动端) */
  3. .container {
  4. width: 100%;
  5. padding: 15px;
  6. }

  7. /* 平板 */
  8. @media screen and (min-width: 768px) {
  9. .container {
  10. width: 750px;
  11. margin: 0 auto;
  12. }
  13. }

  14. /* 桌面 */
  15. @media screen and (min-width: 1024px) {
  16. .container {
  17. width: 970px;
  18. }
  19. }

  20. /* 大屏幕 */
  21. @media screen and (min-width: 1200px) {
  22. .container {
  23. width: 1170px;
  24. }
  25. }
css
3. 响应式布局技巧:
流式布局:
  1. .fluid-layout {
  2. width: 90%;
  3. max-width: 1200px;
  4. margin: 0 auto;
  5. }
css
弹性图片:
  1. .responsive-image {
  2. max-width: 100%;
  3. height: auto;
  4. }
css
弹性字体:
  1. html {
  2. font-size: 16px;
  3. }

  4. @media screen and (max-width: 768px) {
  5. html {
  6. font-size: 14px;
  7. }
  8. }

  9. .text {
  10. font-size: 1rem; /* 相对于根元素的字体大小 */
  11. }
css
响应式网格:
  1. .grid {
  2. display: grid;
  3. grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  4. gap: 20px;
  5. }
css
4. 完整的响应式设计示例:
  1. /* 基础样式 */
  2. :root {
  3. --primary-color: #3498db;
  4. --spacing: 20px;
  5. }

  6. /* 响应式排版 */
  7. html {
  8. font-size: 16px;
  9. }

  10. @media screen and (max-width: 768px) {
  11. html {
  12. font-size: 14px;
  13. }
  14. }

  15. /* 响应式容器 */
  16. .container {
  17. width: 90%;
  18. max-width: 1200px;
  19. margin: 0 auto;
  20. padding: var(--spacing);
  21. }

  22. /* 响应式导航 */
  23. .nav {
  24. display: flex;
  25. justify-content: space-between;
  26. align-items: center;
  27. }

  28. @media screen and (max-width: 768px) {
  29. .nav {
  30. flex-direction: column;
  31. }
  32. .nav-menu {
  33. width: 100%;
  34. display: none; /* 移动端菜单默认隐藏 */
  35. }
  36. .nav-menu.active {
  37. display: block;
  38. }
  39. }

  40. /* 响应式网格 */
  41. .grid {
  42. display: grid;
  43. grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  44. gap: var(--spacing);
  45. }

  46. /* 响应式卡片 */
  47. .card {
  48. background: white;
  49. padding: var(--spacing);
  50. border-radius: 4px;
  51. box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  52. }

  53. @media screen and (max-width: 768px) {
  54. .card {
  55. padding: calc(var(--spacing) / 2);
  56. }
  57. }

  58. /* 响应式表格 */
  59. .table {
  60. width: 100%;
  61. border-collapse: collapse;
  62. }

  63. @media screen and (max-width: 768px) {
  64. .table {
  65. display: block;
  66. overflow-x: auto;
  67. }
  68. }

  69. /* 响应式图片 */
  70. .image {
  71. max-width: 100%;
  72. height: auto;
  73. }

  74. /* 响应式视频 */
  75. .video-container {
  76. position: relative;
  77. padding-bottom: 56.25%; /* 16:9 比例 */
  78. height: 0;
  79. overflow: hidden;
  80. }

  81. .video-container iframe {
  82. position: absolute;
  83. top: 0;
  84. left: 0;
  85. width: 100%;
  86. height: 100%;
  87. }
css
10. CSS3 中的新选择器和伪类/伪元素有哪些?
答案解析:
CSS3 引入了许多新的选择器和伪类/伪元素,大大增强了样式选择的能力。
1. 属性选择器:
  1. /* 精确匹配 */
  2. [data-type="primary"] {
  3. background: blue;
  4. }

  5. /* 开头匹配 */
  6. [class^="btn-"] {
  7. padding: 10px;
  8. }

  9. /* 结尾匹配 */
  10. [href$=".pdf"] {
  11. color: red;
  12. }

  13. /* 包含匹配 */
  14. [title*="hello"] {
  15. font-weight: bold;
  16. }
css
2. 结构性伪类:
  1. /* 第一个子元素 */
  2. :first-child {
  3. margin-top: 0;
  4. }

  5. /* 最后一个子元素 */
  6. :last-child {
  7. margin-bottom: 0;
  8. }

  9. /* 第 n 个子元素 */
  10. :nth-child(2n) {
  11. background: #f0f0f0;
  12. }

  13. /* 第 n 个特定类型的元素 */
  14. p:nth-of-type(odd) {
  15. color: blue;
  16. }
css
3. 状态伪类:
  1. /* 输入框焦点 */
  2. input:focus {
  3. border-color: blue;
  4. }

  5. /* 禁用状态 */
  6. button:disabled {
  7. opacity: 0.5;
  8. }

  9. /* 选中状态 */
  10. input:checked + label {
  11. color: green;
  12. }

  13. /* 必填字段 */
  14. input:required {
  15. border-color: red;
  16. }
css
4. 目标伪类:
  1. /* 当 URL 片段匹配元素 ID 时 */
  2. :target {
  3. background: yellow;
  4. }
css
5. 否定伪类:
  1. /* 选择非特定元素 */
  2. .item:not(.active) {
  3. opacity: 0.5;
  4. }
css
6. 伪元素:
  1. /* 首字母样式 */
  2. p::first-letter {
  3. font-size: 2em;
  4. float: left;
  5. }

  6. /* 首行样式 */
  7. p::first-line {
  8. color: blue;
  9. }

  10. /* 前后插入内容 */
  11. .quote::before {
  12. content: "「";
  13. }
  14. .quote::after {
  15. content: "」";
  16. }

  17. /* 选择文本样式 */
  18. ::selection {
  19. background: yellow;
  20. color: black;
  21. }
css
实际应用示例:
自定义列表样式:
  1. .custom-list {
  2. list-style: none;
  3. padding: 0;
  4. }

  5. .custom-list li::before {
  6. content: "✓";
  7. color: green;
  8. margin-right: 8px;
  9. }
css
卡片悬停效果:
  1. .card {
  2. position: relative;
  3. padding: 20px;
  4. }

  5. .card::after {
  6. content: "";
  7. position: absolute;
  8. top: 0;
  9. left: 0;
  10. width: 100%;
  11. height: 100%;
  12. border: 2px solid transparent;
  13. transition: all 0.3s;
  14. }

  15. .card:hover::after {
  16. border-color: #3498db;
  17. transform: scale(1.05);
  18. }
css
表单验证样式:
  1. .form-input:invalid {
  2. border-color: red;
  3. }

  4. .form-input:invalid::after {
  5. content: "⚠";
  6. color: red;
  7. margin-left: 8px;
  8. }

  9. .form-input:valid {
  10. border-color: green;
  11. }

  12. .form-input:valid::after {
  13. content: "✓";
  14. color: green;
  15. margin-left: 8px;
  16. }
css
交替背景色:
  1. .striped-list li:nth-child(odd) {
  2. background: #f9f9f9;
  3. }

  4. .striped-list li:nth-child(even) {
  5. background: #ffffff;
  6. }
css
高级导航样式:
  1. .nav-link {
  2. position: relative;
  3. padding: 10px;
  4. }

  5. .nav-link::after {
  6. content: "";
  7. position: absolute;
  8. bottom: 0;
  9. left: 50%;
  10. width: 0;
  11. height: 2px;
  12. background: #3498db;
  13. transition: all 0.3s;
  14. transform: translateX(-50%);
  15. }

  16. .nav-link:hover::after {
  17. width: 100%;
  18. }

  19. .nav-link.active::after {
  20. width: 100%;
  21. }
css
JavaScript 核心概念
11. JavaScript 中的数据类型有哪些?如何进行类型判断?
答案解析:
JavaScript 中的数据类型分为两大类:基本数据类型(原始类型)和引用数据类型(对象类型)。
1. 基本数据类型:
Number:数字
String:字符串
Boolean:布尔值
Undefined:未定义
Null:空值
Symbol:符号(ES6)
BigInt:大整数(ES2020)
2. 引用数据类型:
Object:对象
Array:数组
Function:函数
Date:日期
RegExp:正则表达式
Map:映射
Set:集合
Promise:期约
...等
类型判断的方法:
typeof 运算符:
  1. typeof 42; // "number"
  2. typeof "hello"; // "string"
  3. typeof true; // "boolean"
  4. typeof undefined; // "undefined"
  5. typeof Symbol(); // "symbol"
  6. typeof null; // "object" (这是一个历史遗留的bug)
  7. typeof {}; // "object"
  8. typeof []; // "object"
  9. typeof function(){}; // "function"
javascript
instanceof 运算符:
  1. [] instanceof Array; // true
  2. new Date() instanceof Date; // true
  3. /regex/ instanceof RegExp; // true

  4. // 自定义类型判断
  5. class MyClass {}
  6. const obj = new MyClass();
  7. obj instanceof MyClass; // true
javascript
Object.prototype.toString.call():
  1. Object.prototype.toString.call(42); // "[object Number]"
  2. Object.prototype.toString.call("hello"); // "[object String]"
  3. Object.prototype.toString.call(true); // "[object Boolean]"
  4. Object.prototype.toString.call(undefined); // "[object Undefined]"
  5. Object.prototype.toString.call(null); // "[object Null]"
  6. Object.prototype.toString.call({}); // "[object Object]"
  7. Object.prototype.toString.call([]); // "[object Array]"
  8. Object.prototype.toString.call(function(){}); // "[object Function]"
javascript
Array.isArray():
  1. Array.isArray([]); // true
  2. Array.isArray({}); // false
javascript
实际应用示例:
通用类型检查函数:
  1. function getType(value) {
  2. if (value === null) {
  3. return 'null';
  4. }
  5. if (typeof value === 'object') {
  6. return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
  7. }
  8. return typeof value;
  9. }

  10. // 使用示例
  11. getType(42); // "number"
  12. getType("hello"); // "string"
  13. getType(true); // "boolean"
  14. getType(undefined); // "undefined"
  15. getType(null); // "null"
  16. getType({}); // "object"
  17. getType([]); // "array"
  18. getType(function(){}); // "function"
  19. getType(new Date()); // "date"
  20. getType(/regex/); // "regexp"
javascript
类型安全的值比较:
  1. function safelyCompareValues(value1, value2) {
  2. // 首先比较类型
  3. if (getType(value1) !== getType(value2)) {
  4. return false;
  5. }
  6. // 对于数组,递归比较每个元素
  7. if (Array.isArray(value1)) {
  8. if (value1.length !== value2.length) {
  9. return false;
  10. }
  11. return value1.every((item, index) => safelyCompareValues(item, value2[index]));
  12. }
  13. // 对于对象,递归比较每个属性
  14. if (getType(value1) === 'object') {
  15. const keys1 = Object.keys(value1);
  16. const keys2 = Object.keys(value2);
  17. if (keys1.length !== keys2.length) {
  18. return false;
  19. }
  20. return keys1.every(key => safelyCompareValues(value1[key], value2[key]));
  21. }
  22. // 基本类型直接比较
  23. return value1 === value2;
  24. }

  25. // 使用示例
  26. safelyCompareValues([1, 2, 3], [1, 2, 3]); // true
  27. safelyCompareValues([1, 2, 3], [1, 2, '3']); // false
  28. safelyCompareValues({a: 1, b: 2}, {a: 1, b: 2}); // true
  29. safelyCompareValues({a: 1, b: 2}, {b: 2, a: 1}); // true
javascript
类型转换工具:
  1. const TypeConverter = {
  2. toNumber(value) {
  3. if (typeof value === 'number') return value;
  4. if (typeof value === 'string') {
  5. const num = Number(value);
  6. if (!isNaN(num)) return num;
  7. }
  8. throw new TypeError('Cannot convert value to number');
  9. },
  10. toString(value) {
  11. if (value === null) return 'null';
  12. if (value === undefined) return 'undefined';
  13. if (typeof value === 'object') {
  14. return JSON.stringify(value);
  15. }
  16. return String(value);
  17. },
  18. toBoolean(value) {
  19. return Boolean(value);
  20. },
  21. toArray(value) {
  22. if (Array.isArray(value)) return value;
  23. if (typeof value === 'string') return value.split('');
  24. if (value === null || value === undefined) return [];
  25. return [value];
  26. }
  27. };

  28. // 使用示例
  29. TypeConverter.toNumber('123'); // 123
  30. TypeConverter.toString({a: 1}); // "{"a":1}"
  31. TypeConverter.toBoolean(1); // true
  32. TypeConverter.toArray('hello'); // ['h', 'e', 'l', 'l', 'o']
javascript
12. 详细解释 JavaScript 中的作用域和作用域链。
答案解析:
作用域是变量和函数的可访问范围,JavaScript 中主要有全局作用域、函数作用域和块级作用域(ES6)。作用域链则是多个作用域的嵌套关系。
1. 作用域类型:
全局作用域:
  1. var globalVar = 'global'; // 全局变量

  2. function globalFunction() {
  3. console.log(globalVar); // 可以访问全局变量
  4. }
javascript
函数作用域:
  1. function outer() {
  2. var functionVar = 'function'; // 函数作用域变量
  3. function inner() {
  4. console.log(functionVar); // 可以访问外部函数变量
  5. }
  6. inner();
  7. }
javascript
块级作用域(ES6):
  1. {
  2. let blockVar = 'block'; // 块级作用域变量
  3. const constVar = 'const'; // 块级作用域常量
  4. }
  5. // console.log(blockVar); // ReferenceError
javascript
2. 作用域链:
作用域链是由当前作用域到全局作用域的链式查找过程:
  1. var global = 'global';

  2. function outer() {
  3. var outerVar = 'outer';
  4. function inner() {
  5. var innerVar = 'inner';
  6. console.log(innerVar); // 当前作用域
  7. console.log(outerVar); // 外部作用域
  8. console.log(global); // 全局作用域
  9. }
  10. inner();
  11. }
javascript
3. 变量提升:
  1. console.log(hoistedVar); // undefined
  2. var hoistedVar = 'value';

  3. // 等同于:
  4. var hoistedVar;
  5. console.log(hoistedVar);
  6. hoistedVar = 'value';

  7. // 函数声明也会提升
  8. hoistedFunction(); // 可以执行
  9. function hoistedFunction() {
  10. console.log('function hoisted');
  11. }
javascript
4. 闭包和作用域:
  1. function createCounter() {
  2. let count = 0; // 私有变量
  3. return {
  4. increment() {
  5. return ++count;
  6. },
  7. decrement() {
  8. return --count;
  9. },
  10. getCount() {
  11. return count;
  12. }
  13. };
  14. }

  15. const counter = createCounter();
  16. console.log(counter.increment()); // 1
  17. console.log(counter.increment()); // 2
  18. console.log(counter.getCount()); // 2
javascript
5. let/const 和暂时性死区(TDZ):
  1. {
  2. // TDZ 开始
  3. // console.log(blockVar); // ReferenceError
  4. let blockVar = 'block'; // TDZ 结束
  5. const constVar = 'const';
  6. // constVar = 'new value'; // TypeError
  7. }
javascript
实际应用示例:
模块化封装:
  1. const Module = (function() {
  2. // 私有变量和函数
  3. let privateVar = 'private';
  4. function privateFunction() {
  5. return privateVar;
  6. }
  7. // 公共 API
  8. return {
  9. publicMethod() {
  10. return privateFunction();
  11. },
  12. publicVar: 'public'
  13. };
  14. })();

  15. console.log(Module.publicVar); // "public"
  16. console.log(Module.publicMethod()); // "private"
  17. // console.log(Module.privateVar); // undefined
javascript
事件处理器:
  1. function createEventHandler(element, event) {
  2. let count = 0;
  3. element.addEventListener(event, function() {
  4. count++;
  5. console.log(`Event triggered ${count} times`);
  6. });
  7. return {
  8. getCount() {
  9. return count;
  10. },
  11. resetCount() {
  12. count = 0;
  13. }
  14. };
  15. }

  16. const handler = createEventHandler(button, 'click');
  17. // 点击按钮后...
  18. console.log(handler.getCount()); // 显示点击次数
javascript
迭代器生成器:
  1. function createIterator(array) {
  2. let index = 0;
  3. return {
  4. next() {
  5. if (index < array.length) {
  6. return {
  7. value: array[index++],
  8. done: false
  9. };
  10. }
  11. return { done: true };
  12. },
  13. current() {
  14. return array[index];
  15. }
  16. };
  17. }

  18. const iterator = createIterator([1, 2, 3]);
  19. console.log(iterator.next()); // { value: 1, done: false }
  20. console.log(iterator.next()); // { value: 2, done: false }
  21. console.log(iterator.next()); // { value: 3, done: false }
  22. console.log(iterator.next()); // { done: true }
javascript
13. 解释 JavaScript 中的原型和原型链。
答案解析:
原型(Prototype)是 JavaScript 实现继承的主要方式。每个对象都有一个原型对象,对象会从原型"继承"属性和方法。原型链则是由原型对象组成的链式查找机制。
1. 原型基础:
  1. // 构造函数
  2. function Person(name) {
  3. this.name = name;
  4. }

  5. // 原型方法
  6. Person.prototype.sayHello = function() {
  7. return `Hello, I'm ${this.name}`;
  8. };

  9. // 创建实例
  10. const person = new Person('John');
  11. console.log(person.sayHello()); // "Hello, I'm John"

  12. // 原型链查找
  13. console.log(person.__proto__ === Person.prototype); // true
  14. console.log(Person.prototype.__proto__ === Object.prototype); // true
  15. console.log(Object.prototype.__proto__ === null); // true
javascript
2. 继承实现:
原型链继承:
  1. function Animal(name) {
  2. this.name = name;
  3. }

  4. Animal.prototype.speak = function() {
  5. return `${this.name} makes a sound`;
  6. };

  7. function Dog(name) {
  8. Animal.call(this, name); // 调用父类构造函数
  9. }

  10. // 设置原型链
  11. Dog.prototype = Object.create(Animal.prototype);
  12. Dog.prototype.constructor = Dog;

  13. // 添加子类方法
  14. Dog.prototype.bark = function() {
  15. return `${this.name} barks`;
  16. };

  17. const dog = new Dog('Rex');
  18. console.log(dog.speak()); // "Rex makes a sound"
  19. console.log(dog.bark()); // "Rex barks"
javascript
Class 语法(ES6):
  1. class Animal {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. speak() {
  6. return `${this.name} makes a sound`;
  7. }
  8. }

  9. class Dog extends Animal {
  10. constructor(name) {
  11. super(name);
  12. }
  13. bark() {
  14. return `${this.name} barks`;
  15. }
  16. }

  17. const dog = new Dog('Rex');
  18. console.log(dog.speak()); // "Rex makes a sound"
  19. console.log(dog.bark()); // "Rex barks"
javascript
3. 实例方法和静态方法:
  1. class Calculator {
  2. // 实例方法
  3. add(a, b) {
  4. return a + b;
  5. }
  6. // 静态方法
  7. static multiply(a, b) {
  8. return a * b;
  9. }
  10. }

  11. const calc = new Calculator();
  12. console.log(calc.add(1, 2)); // 3
  13. console.log(Calculator.multiply(2, 3)); // 6
javascript
4. 原型方法扩展:
  1. // 扩展内置对象原型
  2. Array.prototype.first = function() {
  3. return this[0];
  4. };

  5. Array.prototype.last = function() {
  6. return this[this.length - 1];
  7. };

  8. const arr = [1, 2, 3];
  9. console.log(arr.first()); // 1
  10. console.log(arr.last()); // 3
javascript
实际应用示例:
组件继承:
  1. class Component {
  2. constructor(props = {}) {
  3. this.props = props;
  4. this.state = {};
  5. }
  6. setState(newState) {
  7. this.state = { ...this.state, ...newState };
  8. this.render();
  9. }
  10. render() {
  11. throw new Error('Component must implement render method');
  12. }
  13. }

  14. class Button extends Component {
  15. constructor(props) {
  16. super(props);
  17. this.state = {
  18. isPressed: false
  19. };
  20. }
  21. toggle() {
  22. this.setState({ isPressed: !this.state.isPressed });
  23. }
  24. render() {
  25. return `<button class="${this.state.isPressed ? 'pressed' : ''}">${this.props.label}button>`;
  26. }
  27. }

  28. const button = new Button({ label: 'Click me' });
  29. console.log(button.render()); // ''
  30. button.toggle();
  31. console.log(button.render()); // ''
javascript
混入(Mixin)模式:
  1. const LoggerMixin = {
  2. log(message) {
  3. console.log(`[${this.constructor.name}] ${message}`);
  4. },
  5. error(message) {
  6. console.error(`[${this.constructor.name}] Error: ${message}`);
  7. }
  8. };

  9. const EventMixin = {
  10. on(event, callback) {
  11. this._events = this._events || {};
  12. this._events[event] = this._events[event] || [];
  13. this._events[event].push(callback);
  14. },
  15. emit(event, data) {
  16. if (this._events && this._events[event]) {
  17. this._events[event].forEach(callback => callback(data));
  18. }
  19. }
  20. };

  21. class UserService {
  22. constructor() {
  23. Object.assign(this, LoggerMixin, EventMixin);
  24. }
  25. login(username) {
  26. this.log(`User ${username} logged in`);
  27. this.emit('login', { username });
  28. }
  29. }

  30. const service = new UserService();
  31. service.on('login', data => console.log('Login event:', data));
  32. service.login('john'); // 输出日志和触发事件
javascript
链式调用:
  1. class Query {
  2. constructor(collection) {
  3. this.collection = collection;
  4. }
  5. filter(predicate) {
  6. this.collection = this.collection.filter(predicate);
  7. return this;
  8. }
  9. map(transform) {
  10. this.collection = this.collection.map(transform);
  11. return this;
  12. }
  13. sort(comparator) {
  14. this.collection = this.collection.sort(comparator);
  15. return this;
  16. }
  17. value() {
  18. return this.collection;
  19. }
  20. }

  21. const data = [
  22. { id: 1, name: 'John', age: 30 },
  23. { id: 2, name: 'Jane', age: 25 },
  24. { id: 3, name: 'Bob', age: 35 }
  25. ];

  26. const result = new Query(data)
  27. .filter(item => item.age > 25)
  28. .map(item => item.name)
  29. .sort()
  30. .value();

  31. console.log(result); // ['Bob', 'John']
javascript
14. 详细解释 JavaScript 中的 this 关键字。
答案解析:
this 关键字是 JavaScript 中最容易混淆的概念之一,它的值取决于函数的调用方式。理解 this 的绑定规则对于编写可靠的 JavaScript 代码至关重要。
1. this 的绑定规则:
默认绑定(非严格模式下指向全局对象,严格模式下指向 undefined):
  1. function showThis() {
  2. console.log(this);
  3. }

  4. showThis(); // window (非严格模式) 或 undefined (严格模式)
javascript
隐式绑定(this 指向调用该方法的对象):
  1. const user = {
  2. name: 'John',
  3. greet() {
  4. console.log(`Hello, ${this.name}!`);
  5. }
  6. };

  7. user.greet(); // "Hello, John!"

  8. // 隐式绑定丢失
  9. const greet = user.greet;
  10. greet(); // "Hello, undefined!" (this 指向全局对象或 undefined)
javascript
显式绑定(使用 call、apply bind):
  1. function greet() {
  2. console.log(`Hello, ${this.name}!`);
  3. }

  4. const user = { name: 'John' };

  5. // call 和 apply 立即调用
  6. greet.call(user); // "Hello, John!"
  7. greet.apply(user); // "Hello, John!"

  8. // bind 返回新函数
  9. const boundGreet = greet.bind(user);
  10. boundGreet(); // "Hello, John!"
javascript
new 绑定(构造函数中的 this 指向新创建的对象):
  1. function User(name) {
  2. this.name = name;
  3. this.greet = function() {
  4. console.log(`Hello, ${this.name}!`);
  5. };
  6. }

  7. const user = new User('John');
  8. user.greet(); // "Hello, John!"
javascript
2. 箭头函数中的 this:
箭头函数没有自己的 this,它继承自外层作用域:
  1. const obj = {
  2. name: 'John',
  3. // 普通函数
  4. greet: function() {
  5. setTimeout(function() {
  6. console.log(`Hello, ${this.name}!`); // this 指向 window
  7. }, 100);
  8. },
  9. // 箭头函数
  10. greetArrow: function() {
  11. setTimeout(() => {
  12. console.log(`Hello, ${this.name}!`); // this 指向 obj
  13. }, 100);
  14. }
  15. };

  16. obj.greet(); // "Hello, undefined!"
  17. obj.greetArrow(); // "Hello, John!"
javascript
3. 常见问题和解决方案:
回调函数中的 this:
  1. class Counter {
  2. constructor() {
  3. this.count = 0;
  4. this.button = document.querySelector('#button');
  5. }
  6. // 问题写法
  7. setup() {
  8. this.button.addEventListener('click', function() {
  9. this.count++; // this 指向 button 元素
  10. });
  11. }
  12. // 解决方案 1:箭头函数
  13. setupArrow() {
  14. this.button.addEventListener('click', () => {
  15. this.count++; // this 指向 Counter 实例
  16. });
  17. }
  18. // 解决方案 2:bind
  19. setupBind() {
  20. this.button.addEventListener('click', function() {
  21. this.count++;
  22. }.bind(this));
  23. }
  24. // 解决方案 3:保存 this
  25. setupSave() {
  26. const self = this;
  27. this.button.addEventListener('click', function() {
  28. self.count++;
  29. });
  30. }
  31. }
javascript
方法作为回调:
  1. class API {
  2. constructor() {
  3. this.baseURL = 'https://api.example.com';
  4. }
  5. // 问题写法
  6. fetch(endpoint) {
  7. return $.get(this.baseURL + endpoint)
  8. .then(function(response) {
  9. this.process(response); // this 是 undefined
  10. });
  11. }
  12. // 解决方案
  13. fetchFixed(endpoint) {
  14. return $.get(this.baseURL + endpoint)
  15. .then(response => {
  16. this.process(response); // this 指向 API 实例
  17. });
  18. }
  19. process(data) {
  20. // 处理数据
  21. }
  22. }
javascript
实际应用示例:
事件处理器类:
  1. class EventHandler {
  2. constructor(element) {
  3. this.element = element;
  4. this.handlers = {};
  5. // 绑定方法
  6. this.handleClick = this.handleClick.bind(this);
  7. this.handleMouseMove = this.handleMouseMove.bind(this);
  8. }
  9. on(event, handler) {
  10. this.handlers[event] = handler.bind(this);
  11. this.element.addEventListener(event, this.handlers[event]);
  12. }
  13. off(event) {
  14. if (this.handlers[event]) {
  15. this.element.removeEventListener(event, this.handlers[event]);
  16. delete this.handlers[event];
  17. }
  18. }
  19. handleClick(event) {
  20. console.log('Clicked at:', event.clientX, event.clientY);
  21. }
  22. handleMouseMove(event) {
  23. console.log('Mouse moved to:', event.clientX, event.clientY);
  24. }
  25. }

  26. const handler = new EventHandler(document.body);
  27. handler.on('click', handler.handleClick);
  28. handler.on('mousemove', handler.handleMouseMove);
javascript
方法装饰器:
  1. function debounce(func, wait) {
  2. let timeout;
  3. return function executedFunction(...args) {
  4. const later = () => {
  5. clearTimeout(timeout);
  6. func.apply(this, args);
  7. };
  8. clearTimeout(timeout);
  9. timeout = setTimeout(later, wait);
  10. };
  11. }

  12. class SearchBox {
  13. constructor() {
  14. this.results = [];
  15. this.search = debounce(this.search.bind(this), 300);
  16. }
  17. async search(query) {
  18. this.results = await fetch(`/api/search?q=${query}`)
  19. .then(res => res.json());
  20. this.render();
  21. }
  22. render() {
  23. // 渲染搜索结果
  24. console.log('Results:', this.results);
  25. }
  26. }
javascript
链式方法调用:
  1. class Calculator {
  2. constructor() {
  3. this.value = 0;
  4. }
  5. add(n) {
  6. this.value += n;
  7. return this;
  8. }
  9. subtract(n) {
  10. this.value -= n;
  11. return this;
  12. }
  13. multiply(n) {
  14. this.value *= n;
  15. return this;
  16. }
  17. divide(n) {
  18. if (n !== 0) {
  19. this.value /= n;
  20. }
  21. return this;
  22. }
  23. power(n) {
  24. this.value = Math.pow(this.value, n);
  25. return this;
  26. }
  27. result() {
  28. return this.value;
  29. }
  30. }

  31. const calc = new Calculator();
  32. const result = calc
  33. .add(5)
  34. .multiply(2)
  35. .subtract(3)
  36. .divide(2)
  37. .power(2)
  38. .result();

  39. console.log(result); // ((5 * 2 - 3) / 2)² = 16
javascript
15. 详细解释 JavaScript 中的异步编程模式。
答案解析:
JavaScript 中的异步编程有多种实现方式,从最早的回调函数,到 Promise,再到 async/await,每种方式都有其特点和应用场景。
1. 回调函数:
  1. // 基本回调
  2. function fetchData(callback) {
  3. setTimeout(() => {
  4. callback('Data fetched');
  5. }, 1000);
  6. }

  7. fetchData(data => {
  8. console.log(data); // "Data fetched"
  9. });

  10. // 回调地狱
  11. fetchUser(userId, function(user) {
  12. fetchPosts(user.id, function(posts) {
  13. fetchComments(posts[0].id, function(comments) {
  14. console.log(comments);
  15. }, handleError);
  16. }, handleError);
  17. }, handleError);
javascript
2. Promise:
  1. // 创建 Promise
  2. function fetchData() {
  3. return new Promise((resolve, reject) => {
  4. setTimeout(() => {
  5. if (Math.random() > 0.5) {
  6. resolve('Success');
  7. } else {
  8. reject('Error');
  9. }
  10. }, 1000);
  11. });
  12. }

  13. // 使用 Promise
  14. fetchData()
  15. .then(data => {
  16. console.log(data);
  17. return processData(data);
  18. })
  19. .then(result => {
  20. console.log(result);
  21. })
  22. .catch(error => {
  23. console.error(error);
  24. });

  25. // Promise.all
  26. Promise.all([
  27. fetch('/api/users'),
  28. fetch('/api/posts'),
  29. fetch('/api/comments')
  30. ])
  31. .then(([users, posts, comments]) => {
  32. // 处理所有结果
  33. })
  34. .catch(error => {
  35. // 处理任何错误
  36. });

  37. // Promise.race
  38. Promise.race([
  39. fetch('/api/fast'),
  40. fetch('/api/slow')
  41. ])
  42. .then(result => {
  43. // 处理最快的响应
  44. });
javascript
3. async/await:
  1. // 基本用法
  2. async function fetchData() {
  3. try {
  4. const response = await fetch('/api/data');
  5. const data = await response.json();
  6. return data;
  7. } catch (error) {
  8. console.error('Error:', error);
  9. }
  10. }

  11. // 并行执行
  12. async function fetchAll() {
  13. try {
  14. const [users, posts, comments] = await Promise.all([
  15. fetch('/api/users'),
  16. fetch('/api/posts'),
  17. fetch('/api/comments')
  18. ]);
  19. return {
  20. users: await users.json(),
  21. posts: await posts.json(),
  22. comments: await comments.json()
  23. };
  24. } catch (error) {
  25. console.error('Error:', error);
  26. }
  27. }

  28. // 错误处理
  29. async function handleErrors() {
  30. try {
  31. const data = await fetchData();
  32. return processData(data);
  33. } catch (error) {
  34. if (error instanceof NetworkError) {
  35. // 处理网络错误
  36. } else if (error instanceof ValidationError) {
  37. // 处理验证错误
  38. } else {
  39. // 处理其他错误
  40. }
  41. } finally {
  42. // 清理工作
  43. }
  44. }
javascript
实际应用示例:
数据加载器:
  1. class DataLoader {
  2. constructor() {
  3. this.cache = new Map();
  4. }
  5. async load(key, fetchFn) {
  6. if (this.cache.has(key)) {
  7. return this.cache.get(key);
  8. }
  9. try {
  10. const data = await fetchFn();
  11. this.cache.set(key, data);
  12. return data;
  13. } catch (error) {
  14. throw new Error(`Failed to load ${key}: ${error.message}`);
  15. }
  16. }
  17. async loadMany(keys, fetchFn) {
  18. return Promise.all(
  19. keys.map(key => this.load(key, () => fetchFn(key)))
  20. );
  21. }
  22. clear(key) {
  23. this.cache.delete(key);
  24. }
  25. clearAll() {
  26. this.cache.clear();
  27. }
  28. }

  29. // 使用示例
  30. const loader = new DataLoader();

  31. // 单个加载
  32. const user = await loader.load('user:1', () =>
  33. fetch('/api/users/1').then(res => res.json())
  34. );

  35. // 批量加载
  36. const users = await loader.loadMany(['user:1', 'user:2'], id =>
  37. fetch(`/api/users/${id}`).then(res => res.json())
  38. );
javascript
请求重试机制:
  1. async function fetchWithRetry(url, options = {}, retries = 3) {
  2. const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
  3. for (let i = 0; i < retries; i++) {
  4. try {
  5. const response = await fetch(url, options);
  6. if (!response.ok) {
  7. throw new Error(`HTTP error! status: ${response.status}`);
  8. }
  9. return await response.json();
  10. } catch (error) {
  11. if (i === retries - 1) throw error;
  12. await delay(Math.pow(2, i) * 1000); // 指数退避
  13. console.log(`Retry attempt ${i + 1} for ${url}`);
  14. }
  15. }
  16. }

  17. // 使用示例
  18. try {
  19. const data = await fetchWithRetry('/api/data');
  20. console.log(data);
  21. } catch (error) {
  22. console.error('All retries failed:', error);
  23. }
javascript
并发控制:
  1. class ConcurrencyManager {
  2. constructor(maxConcurrent = 5) {
  3. this.maxConcurrent = maxConcurrent;
  4. this.running = 0;
  5. this.queue = [];
  6. }
  7. async add(task) {
  8. if (this.running >= this.maxConcurrent) {
  9. await new Promise(resolve => this.queue.push(resolve));
  10. }
  11. this.running++;
  12. try {
  13. return await task();
  14. } finally {
  15. this.running--;
  16. if (this.queue.length > 0) {
  17. const next = this.queue.shift();
  18. next();
  19. }
  20. }
  21. }
  22. async addAll(tasks) {
  23. return Promise.all(tasks.map(task => this.add(task)));
  24. }
  25. }

  26. // 使用示例
  27. const manager = new ConcurrencyManager(3);

  28. const urls = [
  29. '/api/data1',
  30. '/api/data2',
  31. '/api/data3',
  32. '/api/data4',
  33. '/api/data5'
  34. ];

  35. const results = await manager.addAll(
  36. urls.map(url => () => fetch(url).then(res => res.json()))
  37. );
javascript
异步队列处理器:
  1. class AsyncQueue {
  2. constructor() {
  3. this.queue = [];
  4. this.processing = false;
  5. }
  6. async add(task) {
  7. return new Promise((resolve, reject) => {
  8. this.queue.push({ task, resolve, reject });
  9. this.process();
  10. });
  11. }
  12. async process() {
  13. if (this.processing) return;
  14. this.processing = true;
  15. while (this.queue.length > 0) {
  16. const { task, resolve, reject } = this.queue.shift();
  17. try {
  18. const result = await task();
  19. resolve(result);
  20. } catch (error) {
  21. reject(error);
  22. }
  23. }
  24. this.processing = false;
  25. }
  26. clear() {
  27. this.queue = [];
  28. }
  29. get size() {
  30. return this.queue.length;
  31. }
  32. }

  33. // 使用示例
  34. const queue = new AsyncQueue();

  35. // 添加任务
  36. queue.add(async () => {
  37. const response = await fetch('/api/data1');
  38. return response.json();
  39. });

  40. queue.add(async () => {
  41. const response = await fetch('/api/data2');
  42. return response.json();
  43. });

  44. // 批量添加任务
  45. const tasks = urls.map(url => async () => {
  46. const response = await fetch(url);
  47. return response.json();
  48. });

  49. for (const task of tasks) {
  50. await queue.add(task);
  51. }
javascript
16. 解释 JavaScript 中的事件循环(Event Loop)机制。
答案解析:
事件循环是 JavaScript 实现异步编程的核心机制,它负责执行代码、收集和处理事件以及执行队列中的子任务。
1. 基本概念:
调用栈(Call Stack):
存储同步代码执行的上下文
遵循后进先出(LIFO)原则
任务队列(Task Queue):
宏任务(Macrotask):setTimeout, setInterval, setImmediate, I/O, UI rendering
微任务(Microtask):Promise, process.nextTick, MutationObserver
事件循环过程:
执行同步代码(调用栈清空)
执行微任务队列
执行宏任务队列
执行渲染
重复以上步骤
2. 代码示例:
  1. console.log('1'); // 同步代码

  2. setTimeout(() => {
  3. console.log('2'); // 宏任务
  4. }, 0);

  5. Promise.resolve().then(() => {
  6. console.log('3'); // 微任务
  7. });

  8. console.log('4'); // 同步代码

  9. // 输出顺序:1, 4, 3, 2
javascript
3. 实际应用:
任务调度器:
  1. class TaskScheduler {
  2. constructor() {
  3. this.microTasks = [];
  4. this.macroTasks = [];
  5. }
  6. addMicroTask(task) {
  7. Promise.resolve().then(() => task());
  8. }
  9. addMacroTask(task) {
  10. setTimeout(task, 0);
  11. }
  12. schedule(task, type = 'micro') {
  13. if (type === 'micro') {
  14. this.addMicroTask(task);
  15. } else {
  16. this.addMacroTask(task);
  17. }
  18. }
  19. }

  20. // 使用示例
  21. const scheduler = new TaskScheduler();

  22. scheduler.schedule(() => {
  23. console.log('Micro task 1');
  24. });

  25. scheduler.schedule(() => {
  26. console.log('Macro task 1');
  27. }, 'macro');

  28. console.log('Sync task');
javascript
防抖和节流:
  1. // 防抖
  2. function debounce(func, wait) {
  3. let timeout;
  4. return function executedFunction(...args) {
  5. const later = () => {
  6. clearTimeout(timeout);
  7. func.apply(this, args);
  8. };
  9. clearTimeout(timeout);
  10. timeout = setTimeout(later, wait);
  11. };
  12. }

  13. // 节流
  14. function throttle(func, limit) {
  15. let inThrottle;
  16. return function executedFunction(...args) {
  17. if (!inThrottle) {
  18. func.apply(this, args);
  19. inThrottle = true;
  20. setTimeout(() => {
  21. inThrottle = false;
  22. }, limit);
  23. }
  24. };
  25. }

  26. // 使用示例
  27. const debouncedSearch = debounce((query) => {
  28. // 执行搜索
  29. console.log('Searching for:', query);
  30. }, 300);

  31. const throttledScroll = throttle(() => {
  32. // 处理滚动事件
  33. console.log('Scroll event handled');
  34. }, 100);
javascript
异步任务队列:
  1. class AsyncTaskQueue {
  2. constructor() {
  3. this.tasks = [];
  4. this.running = false;
  5. }
  6. enqueue(task) {
  7. return new Promise((resolve, reject) => {
  8. this.tasks.push({ task, resolve, reject });
  9. if (!this.running) {
  10. this.run();
  11. }
  12. });
  13. }
  14. async run() {
  15. this.running = true;
  16. while (this.tasks.length > 0) {
  17. const { task, resolve, reject } = this.tasks.shift();
  18. try {
  19. const result = await task();
  20. resolve(result);
  21. } catch (error) {
  22. reject(error);
  23. }
  24. }
  25. this.running = false;
  26. }
  27. }

  28. // 使用示例
  29. const queue = new AsyncTaskQueue();

  30. // 添加任务
  31. queue.enqueue(async () => {
  32. const result = await fetch('/api/data');
  33. return result.json();
  34. }).then(data => {
  35. console.log('Task 1 completed:', data);
  36. });

  37. queue.enqueue(async () => {
  38. await new Promise(resolve => setTimeout(resolve, 1000));
  39. return 'Task 2 completed';
  40. }).then(message => {
  41. console.log(message);
  42. });
javascript
自定义事件发射器:
  1. class EventEmitter {
  2. constructor() {
  3. this.events = {};
  4. }
  5. on(event, callback) {
  6. if (!this.events[event]) {
  7. this.events[event] = [];
  8. }
  9. this.events[event].push(callback);
  10. return () => this.off(event, callback);
  11. }
  12. off(event, callback) {
  13. if (!this.events[event]) return;
  14. this.events[event] = this.events[event].filter(cb => cb !== callback);
  15. }
  16. emit(event, data) {
  17. if (!this.events[event]) return;
  18. this.events[event].forEach(callback => {
  19. // 使用微任务执行回调
  20. Promise.resolve().then(() => callback(data));
  21. });
  22. }
  23. once(event, callback) {
  24. const remove = this.on(event, (...args) => {
  25. remove();
  26. callback.apply(this, args);
  27. });
  28. }
  29. }

  30. // 使用示例
  31. const emitter = new EventEmitter();

  32. emitter.on('data', data => {
  33. console.log('Received data:', data);
  34. });

  35. emitter.emit('data', { message: 'Hello' });
javascript
17. 详细解释 JavaScript 中常用的设计模式。
答案解析:
设计模式是解决软件设计中常见问题的可复用方案。在 JavaScript 中,常用的设计模式包括创建型模式、结构型模式和行为型模式。
1. 创建型模式:
单例模式:
  1. class Singleton {
  2. constructor() {
  3. if (!Singleton.instance) {
  4. this.data = {};
  5. Singleton.instance = this;
  6. }
  7. return Singleton.instance;
  8. }
  9. static getInstance() {
  10. if (!Singleton.instance) {
  11. Singleton.instance = new Singleton();
  12. }
  13. return Singleton.instance;
  14. }
  15. }

  16. // 使用示例
  17. const instance1 = new Singleton();
  18. const instance2 = new Singleton();
  19. console.log(instance1 === instance2); // true
javascript
工厂模式:
  1. // 简单工厂
  2. class UserFactory {
  3. static createUser(type) {
  4. switch (type) {
  5. case 'admin':
  6. return new AdminUser();
  7. case 'regular':
  8. return new RegularUser();
  9. default:
  10. throw new Error('Unknown user type');
  11. }
  12. }
  13. }

  14. // 工厂方法
  15. class Creator {
  16. factoryMethod() {
  17. throw new Error('factoryMethod must be implemented');
  18. }
  19. someOperation() {
  20. const product = this.factoryMethod();
  21. return product.operation();
  22. }
  23. }

  24. class ConcreteCreatorA extends Creator {
  25. factoryMethod() {
  26. return new ConcreteProductA();
  27. }
  28. }
javascript
建造者模式:
  1. class UserBuilder {
  2. constructor() {
  3. this.user = {};
  4. }
  5. setName(name) {
  6. this.user.name = name;
  7. return this;
  8. }
  9. setAge(age) {
  10. this.user.age = age;
  11. return this;
  12. }
  13. setEmail(email) {
  14. this.user.email = email;
  15. return this;
  16. }
  17. build() {
  18. return this.user;
  19. }
  20. }

  21. // 使用示例
  22. const user = new UserBuilder()
  23. .setName('John')
  24. .setAge(30)
  25. .setEmail('john@example.com')
  26. .build();
javascript
2. 结构型模式:
适配器模式:
  1. // 旧接口
  2. class OldAPI {
  3. getUsers() {
  4. return [{ name: 'John', surname: 'Doe' }];
  5. }
  6. }

  7. // 新接口适配器
  8. class UserAPIAdapter {
  9. constructor(oldAPI) {
  10. this.oldAPI = oldAPI;
  11. }
  12. getUsers() {
  13. return this.oldAPI.getUsers().map(user => ({
  14. fullName: `${user.name} ${user.surname}`
  15. }));
  16. }
  17. }

  18. // 使用示例
  19. const oldAPI = new OldAPI();
  20. const adapter = new UserAPIAdapter(oldAPI);
  21. console.log(adapter.getUsers()); // [{ fullName: 'John Doe' }]
javascript
装饰器模式:
  1. class Coffee {
  2. cost() {
  3. return 5;
  4. }
  5. description() {
  6. return 'Simple coffee';
  7. }
  8. }

  9. class MilkDecorator {
  10. constructor(coffee) {
  11. this.coffee = coffee;
  12. }
  13. cost() {
  14. return this.coffee.cost() + 2;
  15. }
  16. description() {
  17. return `${this.coffee.description()} with milk`;
  18. }
  19. }

  20. // 使用示例
  21. let coffee = new Coffee();
  22. coffee = new MilkDecorator(coffee);
  23. console.log(coffee.cost()); // 7
  24. console.log(coffee.description()); // "Simple coffee with milk"
javascript
代理模式:
  1. class RealImage {
  2. constructor(filename) {
  3. this.filename = filename;
  4. this.loadImage();
  5. }
  6. loadImage() {
  7. console.log(`Loading ${this.filename}`);
  8. }
  9. display() {
  10. console.log(`Displaying ${this.filename}`);
  11. }
  12. }

  13. class ProxyImage {
  14. constructor(filename) {
  15. this.filename = filename;
  16. this.realImage = null;
  17. }
  18. display() {
  19. if (!this.realImage) {
  20. this.realImage = new RealImage(this.filename);
  21. }
  22. this.realImage.display();
  23. }
  24. }

  25. // 使用示例
  26. const image = new ProxyImage('photo.jpg');
  27. // 图片只在需要时才加载
  28. image.display();
javascript
3. 行为型模式:
观察者模式:
  1. class Subject {
  2. constructor() {
  3. this.observers = [];
  4. }
  5. addObserver(observer) {
  6. this.observers.push(observer);
  7. }
  8. removeObserver(observer) {
  9. this.observers = this.observers.filter(obs => obs !== observer);
  10. }
  11. notify(data) {
  12. this.observers.forEach(observer => observer.update(data));
  13. }
  14. }

  15. class Observer {
  16. update(data) {
  17. console.log('Received update:', data);
  18. }
  19. }

  20. // 使用示例
  21. const subject = new Subject();
  22. const observer1 = new Observer();
  23. const observer2 = new Observer();

  24. subject.addObserver(observer1);
  25. subject.addObserver(observer2);
  26. subject.notify('Hello observers!');
javascript
策略模式:
  1. class PaymentStrategy {
  2. pay(amount) {
  3. throw new Error('pay() must be implemented');
  4. }
  5. }

  6. class CreditCardStrategy extends PaymentStrategy {
  7. constructor(cardNumber, cvv) {
  8. super();
  9. this.cardNumber = cardNumber;
  10. this.cvv = cvv;
  11. }
  12. pay(amount) {
  13. console.log(`Paid ${amount} using credit card`);
  14. }
  15. }

  16. class PayPalStrategy extends PaymentStrategy {
  17. constructor(email) {
  18. super();
  19. this.email = email;
  20. }
  21. pay(amount) {
  22. console.log(`Paid ${amount} using PayPal`);
  23. }
  24. }

  25. class ShoppingCart {
  26. constructor() {
  27. this.amount = 0;
  28. this.paymentStrategy = null;
  29. }
  30. setPaymentStrategy(strategy) {
  31. this.paymentStrategy = strategy;
  32. }
  33. checkout() {
  34. if (!this.paymentStrategy) {
  35. throw new Error('Payment strategy not set');
  36. }
  37. this.paymentStrategy.pay(this.amount);
  38. }
  39. }

  40. // 使用示例
  41. const cart = new ShoppingCart();
  42. cart.amount = 100;
  43. cart.setPaymentStrategy(new CreditCardStrategy('1234', '123'));
  44. cart.checkout();
javascript
命令模式:
  1. class Command {
  2. execute() {
  3. throw new Error('execute() must be implemented');
  4. }
  5. undo() {
  6. throw new Error('undo() must be implemented');
  7. }
  8. }

  9. class AddTextCommand extends Command {
  10. constructor(editor, text) {
  11. super();
  12. this.editor = editor;
  13. this.text = text;
  14. }
  15. execute() {
  16. this.editor.addText(this.text);
  17. }
  18. undo() {
  19. this.editor.removeText(this.text);
  20. }
  21. }

  22. class Editor {
  23. constructor() {
  24. this.content = '';
  25. }
  26. addText(text) {
  27. this.content += text;
  28. }
  29. removeText(text) {
  30. this.content = this.content.replace(text, '');
  31. }
  32. }

  33. class CommandHistory {
  34. constructor() {
  35. this.history = [];
  36. this.current = -1;
  37. }
  38. execute(command) {
  39. command.execute();
  40. this.history.push(command);
  41. this.current++;
  42. }
  43. undo() {
  44. if (this.current >= 0) {
  45. this.history[this.current].undo();
  46. this.current--;
  47. }
  48. }
  49. redo() {
  50. if (this.current < this.history.length - 1) {
  51. this.current++;
  52. this.history[this.current].execute();
  53. }
  54. }
  55. }

  56. // 使用示例
  57. const editor = new Editor();
  58. const history = new CommandHistory();

  59. const addHelloCommand = new AddTextCommand(editor, 'Hello ');
  60. const addWorldCommand = new AddTextCommand(editor, 'World!');

  61. history.execute(addHelloCommand);
  62. history.execute(addWorldCommand);
  63. console.log(editor.content); // "Hello World!"

  64. history.undo();
  65. console.log(editor.content); // "Hello "

  66. history.redo();
  67. console.log(editor.content); // "Hello World!"
javascript
实际应用场景:
表单验证策略:
  1. class ValidationStrategy {
  2. validate(value) {
  3. throw new Error('validate() must be implemented');
  4. }
  5. }

  6. class RequiredFieldStrategy extends ValidationStrategy {
  7. validate(value) {
  8. return value.trim().length > 0;
  9. }
  10. }

  11. class EmailStrategy extends ValidationStrategy {
  12. validate(value) {
  13. return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
  14. }
  15. }

  16. class PasswordStrategy extends ValidationStrategy {
  17. validate(value) {
  18. return value.length >= 8 && /[A-Z]/.test(value) && /[0-9]/.test(value);
  19. }
  20. }

  21. class FormValidator {
  22. constructor() {
  23. this.validations = new Map();
  24. }
  25. addValidation(field, strategy) {
  26. this.validations.set(field, strategy);
  27. }
  28. validate(formData) {
  29. const errors = new Map();
  30. for (const [field, strategy] of this.validations) {
  31. if (!strategy.validate(formData[field])) {
  32. errors.set(field, `${field} is invalid`);
  33. }
  34. }
  35. return errors;
  36. }
  37. }

  38. // 使用示例
  39. const validator = new FormValidator();
  40. validator.addValidation('email', new EmailStrategy());
  41. validator.addValidation('password', new PasswordStrategy());

  42. const formData = {
  43. email: 'invalid-email',
  44. password: 'weak'
  45. };

  46. const errors = validator.validate(formData);
  47. console.log(errors);
javascript
状态管理:
  1. class State {
  2. constructor(context) {
  3. this.context = context;
  4. }
  5. handle() {
  6. throw new Error('handle() must be implemented');
  7. }
  8. }

  9. class PlayingState extends State {
  10. handle() {
  11. console.log('Playing...');
  12. this.context.setState(new PausedState(this.context));
  13. }
  14. }

  15. class PausedState extends State {
  16. handle() {
  17. console.log('Paused');
  18. this.context.setState(new PlayingState(this.context));
  19. }
  20. }

  21. class AudioPlayer {
  22. constructor() {
  23. this.state = new PausedState(this);
  24. }
  25. setState(state) {
  26. this.state = state;
  27. }
  28. toggle() {
  29. this.state.handle();
  30. }
  31. }

  32. // 使用示例
  33. const player = new AudioPlayer();
  34. player.toggle(); // "Playing..."
  35. player.toggle(); // "Paused"
  36. player.toggle(); // "Playing..."
javascript
数据访问代理:
  1. class DataService {
  2. constructor() {
  3. this.cache = new Map();
  4. }
  5. async fetchData(url) {
  6. if (this.cache.has(url)) {
  7. console.log('Returning from cache');
  8. return this.cache.get(url);
  9. }
  10. console.log('Fetching from server');
  11. const response = await fetch(url);
  12. const data = await response.json();
  13. this.cache.set(url, data);
  14. return data;
  15. }
  16. clearCache() {
  17. this.cache.clear();
  18. }
  19. }

  20. // 使用示例
  21. const service = new DataService();

  22. // 第一次调用:从服务器获取
  23. await service.fetchData('/api/data');

  24. // 第二次调用:从缓存获取
  25. await service.fetchData('/api/data');
javascript
18. 详细解释 ES6+ 中的新特性。
答案解析:
ES6(ES2015)及后续版本引入了许多重要的新特性,极大地提升了 JavaScript 的开发体验和功能性。
1. 变量声明:
let const:
  1. // let:块级作用域
  2. {
  3. let x = 1;
  4. const y = 2;
  5. }
  6. // console.log(x); // ReferenceError

  7. // const:常量声明
  8. const PI = 3.14159;
  9. // PI = 3; // TypeError

  10. // 对象和数组的 const
  11. const obj = { a: 1 };
  12. obj.a = 2; // 可以修改属性
  13. // obj = {}; // TypeError

  14. const arr = [1, 2];
  15. arr.push(3); // 可以修改数组
  16. // arr = []; // TypeError
javascript
2. 解构赋值:
数组解构:
  1. const [a, b, ...rest] = [1, 2, 3, 4, 5];
  2. console.log(a); // 1
  3. console.log(b); // 2
  4. console.log(rest); // [3, 4, 5]

  5. // 设置默认值
  6. const [x = 1, y = 2] = [10];
  7. console.log(x, y); // 10, 2

  8. // 交换变量
  9. let m = 1, n = 2;
  10. [m, n] = [n, m];
javascript
对象解构:
  1. const { name, age, address: { city } = {} } = {
  2. name: 'John',
  3. age: 30,
  4. address: { city: 'New York' }
  5. };

  6. // 重命名
  7. const { name: userName } = { name: 'John' };
  8. console.log(userName); // "John"

  9. // 默认值
  10. const { x = 1, y = 2 } = { x: 10 };
  11. console.log(x, y); // 10, 2
javascript
3. 模板字符串:
  1. const name = 'John';
  2. const age = 30;

  3. // 基本用法
  4. const message = `Hello, ${name}!`;

  5. // 多行字符串
  6. const template = `
  7. <div>
  8. <h1>${name}h1>
  9. <p>Age: ${age}p>
  10. div>
  11. `;

  12. // 标签模板
  13. function tag(strings, ...values) {
  14. return strings.reduce((result, str, i) =>
  15. `${result}${str}${values[i] || ''}`, '');
  16. }

  17. const text = tag`Hello ${name}, you are ${age} years old`;
javascript
4. 箭头函数:
  1. // 基本语法
  2. const add = (a, b) => a + b;

  3. // 返回对象字面量
  4. const getUser = () => ({ name: 'John', age: 30 });

  5. // this 绑定
  6. class Counter {
  7. constructor() {
  8. this.count = 0;
  9. this.increment = () => {
  10. this.count++;
  11. };
  12. }
  13. }

  14. // 不适合使用箭头函数的场景
  15. const obj = {
  16. name: 'John',
  17. // 方法定义不要使用箭头函数
  18. getName: () => this.name, // this 指向外部作用域
  19. getNameCorrect() {
  20. return this.name;
  21. }
  22. };
javascript
5. 类和模块:
类:
  1. class Animal {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. static create(name) {
  6. return new Animal(name);
  7. }
  8. speak() {
  9. return `${this.name} makes a sound`;
  10. }
  11. }

  12. class Dog extends Animal {
  13. constructor(name, breed) {
  14. super(name);
  15. this.breed = breed;
  16. }
  17. speak() {
  18. return `${super.speak()} - woof!`;
  19. }
  20. get info() {
  21. return `${this.name} is a ${this.breed}`;
  22. }
  23. set nickname(value) {
  24. this._nickname = value;
  25. }
  26. }

  27. const dog = new Dog('Rex', 'German Shepherd');
javascript
模块:
  1. // math.js
  2. export const add = (a, b) => a + b;
  3. export const subtract = (a, b) => a - b;
  4. export default class Calculator {
  5. // ...
  6. }

  7. // main.js
  8. import Calculator, { add, subtract } from './math.js';
  9. import * as math from './math.js';
javascript
6. Promise 和异步编程:
  1. // Promise 链式调用
  2. fetch('/api/user')
  3. .then(response => response.json())
  4. .then(user => fetch(`/api/posts/${user.id}`))
  5. .then(response => response.json())
  6. .catch(error => console.error(error));

  7. // Promise.all
  8. Promise.all([
  9. fetch('/api/users'),
  10. fetch('/api/posts'),
  11. fetch('/api/comments')
  12. ])
  13. .then(([users, posts, comments]) => {
  14. // 处理所有响应
  15. });

  16. // Promise.race
  17. Promise.race([
  18. fetch('/api/fast'),
  19. fetch('/api/slow')
  20. ])
  21. .then(result => {
  22. // 处理最快的响应
  23. });

  24. // async/await
  25. async function fetchUserData() {
  26. try {
  27. const response = await fetch('/api/user');
  28. const user = await response.json();
  29. return user;
  30. } catch (error) {
  31. console.error(error);
  32. }
  33. }
javascript
7. 迭代器和生成器:
  1. // 迭代器
  2. const array = ['a', 'b', 'c'];
  3. const iterator = array[Symbol.iterator]();
  4. console.log(iterator.next()); // { value: 'a', done: false }

  5. // 自定义迭代器
  6. class Range {
  7. constructor(start, end) {
  8. this.start = start;
  9. this.end = end;
  10. }
  11. [Symbol.iterator]() {
  12. let current = this.start;
  13. const end = this.end;
  14. return {
  15. next() {
  16. return current <= end
  17. ? { value: current++, done: false }
  18. : { done: true };
  19. }
  20. };
  21. }
  22. }

  23. // 生成器
  24. function* numberGenerator() {
  25. yield 1;
  26. yield 2;
  27. yield 3;
  28. }

  29. const gen = numberGenerator();
  30. console.log(gen.next()); // { value: 1, done: false }

  31. // 无限序列
  32. function* fibonacci() {
  33. let prev = 0, curr = 1;
  34. while (true) {
  35. yield curr;
  36. [prev, curr] = [curr, prev + curr];
  37. }
  38. }

  39. // 异步生成器
  40. async function* asyncGenerator() {
  41. const responses = [
  42. await fetch('/api/data1'),
  43. await fetch('/api/data2'),
  44. await fetch('/api/data3')
  45. ];
  46. for (const response of responses) {
  47. yield await response.json();
  48. }
  49. }
javascript
8. Set Map:
  1. // Set
  2. const set = new Set([1, 2, 2, 3, 3, 4]);
  3. console.log(set.size); // 4

  4. set.add(5);
  5. set.delete(1);
  6. console.log(set.has(2)); // true

  7. // WeakSet
  8. const weakSet = new WeakSet();
  9. let obj = { data: 123 };
  10. weakSet.add(obj);

  11. // Map
  12. const map = new Map();
  13. map.set('name', 'John');
  14. map.set(obj, 'metadata');

  15. console.log(map.get('name')); // "John"
  16. console.log(map.has(obj)); // true

  17. // WeakMap
  18. const weakMap = new WeakMap();
  19. weakMap.set(obj, 'private data');
javascript
9. Proxy Reflect:
  1. // Proxy
  2. const handler = {
  3. get(target, prop) {
  4. console.log(`Accessing ${prop}`);
  5. return target[prop];
  6. },
  7. set(target, prop, value) {
  8. console.log(`Setting ${prop} = ${value}`);
  9. target[prop] = value;
  10. return true;
  11. }
  12. };

  13. const user = new Proxy({}, handler);
  14. user.name = 'John'; // "Setting name = John"
  15. console.log(user.name); // "Accessing name", "John"

  16. // Reflect
  17. const obj = { name: 'John' };
  18. console.log(Reflect.get(obj, 'name')); // "John"
  19. Reflect.set(obj, 'age', 30);
  20. console.log(Reflect.has(obj, 'age')); // true
javascript
10. 其他特性:
可选链操作符:
  1. const user = {
  2. address: {
  3. street: 'Main St'
  4. }
  5. };

  6. console.log(user?.address?.street); // "Main St"
  7. console.log(user?.contact?.phone); // undefined
javascript
空值合并操作符:
  1. const value = null ?? 'default';
  2. console.log(value); // "default"

  3. const count = 0 ?? 42;
  4. console.log(count); // 0
javascript
逻辑赋值操作符:
  1. let x = null;
  2. x ??= 42;
  3. console.log(x); // 42

  4. let y = 0;
  5. y ||= 42;
  6. console.log(y); // 42

  7. let z = 1;
  8. z &&= 42;
  9. console.log(z); // 42
javascript
BigInt:
  1. const bigInt = 9007199254740991n;
  2. const result = bigInt + 1n;
  3. console.log(result); // 9007199254740992n
javascript
globalThis:
  1. // 在任何环境下都指向全局对象
  2. console.log(globalThis === window); // true (在浏览器中)
  3. console.log(globalThis === global); // true (在 Node.js 中)
javascript
实际应用示例:
现代模块化开发:
  1. // api.js
  2. export class API {
  3. constructor(baseURL) {
  4. this.baseURL = baseURL;
  5. }
  6. async fetch(endpoint, options = {}) {
  7. const response = await fetch(`${this.baseURL}${endpoint}`, {
  8. headers: {
  9. 'Content-Type': 'application/json',
  10. ...options.headers
  11. },
  12. ...options
  13. });
  14. if (!response.ok) {
  15. throw new Error(`HTTP error! status: ${response.status}`);
  16. }
  17. return response.json();
  18. }
  19. }

  20. // services.js
  21. import { API } from './api.js';

  22. export class UserService {
  23. constructor(api) {
  24. this.api = api;
  25. }
  26. async getUser(id) {
  27. return this.api.fetch(`/users/${id}`);
  28. }
  29. async updateUser(id, data) {
  30. return this.api.fetch(`/users/${id}`, {
  31. method: 'PUT',
  32. body: JSON.stringify(data)
  33. });
  34. }
  35. }

  36. // main.js
  37. import { API } from './api.js';
  38. import { UserService } from './services.js';

  39. const api = new API('https://api.example.com');
  40. const userService = new UserService(api);

  41. async function init() {
  42. try {
  43. const user = await userService.getUser(1);
  44. console.log(user);
  45. } catch (error) {
  46. console.error(error);
  47. }
  48. }
javascript
响应式数据绑定:
  1. class Observable {
  2. constructor(value) {
  3. this._value = value;
  4. this._subscribers = new Set();
  5. return new Proxy(this, {
  6. get: (target, prop) => {
  7. if (prop === 'value') {
  8. return target._value;
  9. }
  10. return target[prop];
  11. },
  12. set: (target, prop, value) => {
  13. if (prop === 'value') {
  14. target._value = value;
  15. target.notify();
  16. } else {
  17. target[prop] = value;
  18. }
  19. return true;
  20. }
  21. });
  22. }
  23. subscribe(callback) {
  24. this._subscribers.add(callback);
  25. return () => this._subscribers.delete(callback);
  26. }
  27. notify() {
  28. for (const callback of this._subscribers) {
  29. callback(this._value);
  30. }
  31. }
  32. }

  33. // 使用示例
  34. const counter = new Observable(0);
  35. const unsubscribe = counter.subscribe(value => {
  36. console.log('Counter changed:', value);
  37. });

  38. counter.value++; // "Counter changed: 1"
  39. counter.value++; // "Counter changed: 2"

  40. unsubscribe(); // 取消订阅
javascript
异步任务队列:
  1. class AsyncQueue {
  2. constructor() {
  3. this.queue = [];
  4. this.running = false;
  5. }
  6. async *[Symbol.asyncIterator]() {
  7. while (true) {
  8. if (this.queue.length === 0) {
  9. await new Promise(resolve => {
  10. this.queue.push = (...items) => {
  11. Array.prototype.push.apply(this.queue, items);
  12. resolve();
  13. this.queue.push = Array.prototype.push;
  14. };
  15. });
  16. }
  17. yield this.queue.shift();
  18. }
  19. }
  20. enqueue(...items) {
  21. this.queue.push(...items);
  22. }
  23. async process(callback) {
  24. if (this.running) return;
  25. this.running = true;
  26. try {
  27. for await (const item of this) {
  28. await callback(item);
  29. }
  30. } finally {
  31. this.running = false;
  32. }
  33. }
  34. }

  35. // 使用示例
  36. const queue = new AsyncQueue();

  37. // 启动处理
  38. queue.process(async item => {
  39. console.log('Processing:', item);
  40. await new Promise(resolve => setTimeout(resolve, 1000));
  41. });

  42. // 添加任务
  43. queue.enqueue('Task 1', 'Task 2', 'Task 3');

  44. // 稍后添加更多任务
  45. setTimeout(() => {
  46. queue.enqueue('Task 4', 'Task 5');
  47. }, 3000);
javascript
19. 详细解释 ES6+ 中的装饰器(Decorator)。
答案解析:
装饰器是一种特殊类型的声明,它能够被附加到类声明、方法、访问符、属性或参数上。装饰器使用 @expression 这种形式,expression 求值后必须为一个函数。
1. 类装饰器:
  1. // 类装饰器
  2. function log(target) {
  3. // 保存原始构造函数
  4. const original = target;
  5. // 返回新的构造函数
  6. function construct(constructor, args) {
  7. console.log(`Creating new instance of ${constructor.name}`);
  8. const instance = new constructor(...args);
  9. return instance;
  10. }
  11. // 创建新的类
  12. const newConstructor = function (...args) {
  13. return construct(original, args);
  14. };
  15. // 复制原型链
  16. newConstructor.prototype = original.prototype;
  17. return newConstructor;
  18. }

  19. @log
  20. class Example {
  21. constructor(name) {
  22. this.name = name;
  23. }
  24. }

  25. const example = new Example('test'); // 输出: "Creating new instance of Example"
javascript
2. 方法装饰器:
  1. // 方法装饰器
  2. function measure(target, propertyKey, descriptor) {
  3. const originalMethod = descriptor.value;
  4. descriptor.value = function (...args) {
  5. const start = performance.now();
  6. const result = originalMethod.apply(this, args);
  7. const end = performance.now();
  8. console.log(`${propertyKey} took ${end - start}ms`);
  9. return result;
  10. };
  11. return descriptor;
  12. }

  13. class Calculator {
  14. @measure
  15. add(a, b) {
  16. return a + b;
  17. }
  18. }

  19. const calc = new Calculator();
  20. calc.add(1, 2); // 输出执行时间
javascript
3. 属性装饰器:
  1. // 属性装饰器
  2. function readonly(target, propertyKey) {
  3. Object.defineProperty(target, propertyKey, {
  4. writable: false
  5. });
  6. }

  7. class Example {
  8. @readonly
  9. pi = 3.14159;
  10. }

  11. const e = new Example();
  12. // e.pi = 3; // TypeError: Cannot assign to read only property 'pi'
javascript
4. 参数装饰器:
  1. // 参数装饰器
  2. function validate(target, propertyKey, parameterIndex) {
  3. const validateParams = target[propertyKey].validateParams || [];
  4. validateParams[parameterIndex] = true;
  5. target[propertyKey].validateParams = validateParams;
  6. }

  7. class UserService {
  8. createUser(@validate name: string, @validate age: number) {
  9. // 实现创建用户的逻辑
  10. }
  11. }
javascript
5. 多个装饰器组合:
  1. // 装饰器组合
  2. function first() {
  3. console.log("first(): factory evaluated");
  4. return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  5. console.log("first(): called");
  6. };
  7. }

  8. function second() {
  9. console.log("second(): factory evaluated");
  10. return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  11. console.log("second(): called");
  12. };
  13. }

  14. class Example {
  15. @first()
  16. @second()
  17. method() {}
  18. }

  19. // 输出顺序:
  20. // first(): factory evaluated
  21. // second(): factory evaluated
  22. // second(): called
  23. // first(): called
javascript
实际应用示例:
日志记录装饰器:
  1. function log(target, propertyKey, descriptor) {
  2. const originalMethod = descriptor.value;
  3. descriptor.value = function (...args) {
  4. console.log(`Calling ${propertyKey} with args:`, args);
  5. try {
  6. const result = originalMethod.apply(this, args);
  7. console.log(`${propertyKey} returned:`, result);
  8. return result;
  9. } catch (error) {
  10. console.error(`${propertyKey} threw error:`, error);
  11. throw error;
  12. }
  13. };
  14. return descriptor;
  15. }

  16. class UserService {
  17. @log
  18. async createUser(userData) {
  19. // 实现创建用户的逻辑
  20. }
  21. @log
  22. async updateUser(id, userData) {
  23. // 实现更新用户的逻辑
  24. }
  25. }
javascript
缓存装饰器:
  1. function memoize(target, propertyKey, descriptor) {
  2. const originalMethod = descriptor.value;
  3. const cache = new Map();
  4. descriptor.value = function (...args) {
  5. const key = JSON.stringify(args);
  6. if (cache.has(key)) {
  7. return cache.get(key);
  8. }
  9. const result = originalMethod.apply(this, args);
  10. cache.set(key, result);
  11. return result;
  12. };
  13. return descriptor;
  14. }

  15. class MathUtils {
  16. @memoize
  17. fibonacci(n) {
  18. if (n <= 1) return n;
  19. return this.fibonacci(n - 1) + this.fibonacci(n - 2);
  20. }
  21. }
javascript
权限控制装饰器:
  1. function requireRole(role) {
  2. return function (target, propertyKey, descriptor) {
  3. const originalMethod = descriptor.value;
  4. descriptor.value = function (...args) {
  5. const user = getCurrentUser(); // 假设这个函数获取当前用户
  6. if (!user || !user.roles.includes(role)) {
  7. throw new Error('Unauthorized');
  8. }
  9. return originalMethod.apply(this, args);
  10. };
  11. return descriptor;
  12. };
  13. }

  14. class AdminPanel {
  15. @requireRole('admin')
  16. deleteUser(userId) {
  17. // 实现删除用户的逻辑
  18. }
  19. @requireRole('moderator')
  20. banUser(userId) {
  21. // 实现封禁用户的逻辑
  22. }
  23. }
javascript
防抖装饰器:
  1. function debounce(wait) {
  2. return function (target, propertyKey, descriptor) {
  3. const originalMethod = descriptor.value;
  4. let timeout;
  5. descriptor.value = function (...args) {
  6. clearTimeout(timeout);
  7. timeout = setTimeout(() => {
  8. originalMethod.apply(this, args);
  9. }, wait);
  10. };
  11. return descriptor;
  12. };
  13. }

  14. class SearchComponent {
  15. @debounce(300)
  16. search(query) {
  17. // 实现搜索逻辑
  18. }
  19. }
javascript
验证装饰器:
  1. function validate(schema) {
  2. return function (target, propertyKey, descriptor) {
  3. const originalMethod = descriptor.value;
  4. descriptor.value = function (...args) {
  5. const validationResult = schema.validate(args[0]);
  6. if (validationResult.error) {
  7. throw new Error(validationResult.error.message);
  8. }
  9. return originalMethod.apply(this, args);
  10. };
  11. return descriptor;
  12. };
  13. }

  14. const userSchema = {
  15. validate(data) {
  16. const errors = [];
  17. if (!data.name) errors.push('Name is required');
  18. if (!data.email) errors.push('Email is required');
  19. return {
  20. error: errors.length ? { message: errors.join(', ') } : null
  21. };
  22. }
  23. };

  24. class UserController {
  25. @validate(userSchema)
  26. createUser(userData) {
  27. // 实现创建用户的逻辑
  28. }
  29. }
javascript
20. 详细解释 ES6+ 中的 Reflect Proxy API。
答案解析:
Reflect Proxy API 提供了拦截和自定义对象操作的能力,是实现元编程的重要工具。
1. Reflect API:
Reflect 是一个内置的对象,它提供拦截 JavaScript 操作的方法。
  1. // 基本操作
  2. const obj = { name: 'John' };

  3. // 获取属性
  4. console.log(Reflect.get(obj, 'name')); // "John"

  5. // 设置属性
  6. Reflect.set(obj, 'age', 30);

  7. // 删除属性
  8. Reflect.deleteProperty(obj, 'age');

  9. // 检查属性
  10. console.log(Reflect.has(obj, 'name')); // true

  11. // 获取所有属性
  12. console.log(Reflect.ownKeys(obj)); // ["name"]

  13. // 创建对象
  14. const instance = Reflect.construct(Array, [1, 2, 3]);

  15. // 调用函数
  16. const result = Reflect.apply(Math.max, null, [1, 2, 3]);
javascript
2. Proxy API:
Proxy 用于创建一个对象的代理,从而实现基本操作的拦截和自定义。
  1. // 基本用法
  2. const target = {
  3. name: 'John',
  4. age: 30
  5. };

  6. const handler = {
  7. get(target, prop) {
  8. console.log(`Accessing ${prop}`);
  9. return target[prop];
  10. },
  11. set(target, prop, value) {
  12. console.log(`Setting ${prop} = ${value}`);
  13. target[prop] = value;
  14. return true;
  15. }
  16. };

  17. const proxy = new Proxy(target, handler);

  18. // 使用代理
  19. proxy.name; // "Accessing name"
  20. proxy.age = 31; // "Setting age = 31"
javascript
3. 常用的代理处理器:
  1. const handler = {
  2. // 属性读取
  3. get(target, prop) {
  4. return target[prop];
  5. },
  6. // 属性设置
  7. set(target, prop, value) {
  8. target[prop] = value;
  9. return true;
  10. },
  11. // 属性删除
  12. deleteProperty(target, prop) {
  13. return delete target[prop];
  14. },
  15. // 属性存在性判断
  16. has(target, prop) {
  17. return prop in target;
  18. },
  19. // 获取属性描述符
  20. getOwnPropertyDescriptor(target, prop) {
  21. return Object.getOwnPropertyDescriptor(target, prop);
  22. },
  23. // 定义属性
  24. defineProperty(target, prop, descriptor) {
  25. return Object.defineProperty(target, prop, descriptor);
  26. },
  27. // 获取原型
  28. getPrototypeOf(target) {
  29. return Object.getPrototypeOf(target);
  30. },
  31. // 设置原型
  32. setPrototypeOf(target, proto) {
  33. return Object.setPrototypeOf(target, proto);
  34. }
  35. };
javascript
实际应用示例:
私有属性代理:
  1. function createPrivateProxy(target) {
  2. const privateProps = new WeakMap();
  3. return new Proxy(target, {
  4. get(target, prop) {
  5. if (prop.startsWith('_')) {
  6. throw new Error('Cannot access private property');
  7. }
  8. return target[prop];
  9. },
  10. set(target, prop, value) {
  11. if (prop.startsWith('_')) {
  12. privateProps.set(target, {
  13. ...privateProps.get(target),
  14. [prop]: value
  15. });
  16. } else {
  17. target[prop] = value;
  18. }
  19. return true;
  20. }
  21. });
  22. }

  23. class User {
  24. constructor(name) {
  25. this._password = 'secret';
  26. this.name = name;
  27. }
  28. }

  29. const user = createPrivateProxy(new User('John'));
  30. console.log(user.name); // "John"
  31. // console.log(user._password); // Error: Cannot access private property
javascript
验证代理:
  1. function createValidationProxy(target, validations) {
  2. return new Proxy(target, {
  3. set(target, prop, value) {
  4. if (validations[prop]) {
  5. const validation = validations[prop];
  6. if (!validation(value)) {
  7. throw new Error(`Invalid value for ${prop}`);
  8. }
  9. }
  10. target[prop] = value;
  11. return true;
  12. }
  13. });
  14. }

  15. const user = createValidationProxy({}, {
  16. age: value => typeof value === 'number' && value >= 0 && value <= 120,
  17. email: value => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
  18. });

  19. user.age = 30; // OK
  20. // user.age = -1; // Error: Invalid value for age
  21. user.email = 'john@example.com'; // OK
  22. // user.email = 'invalid'; // Error: Invalid value for email
javascript
日志代理:
  1. function createLoggingProxy(target, name) {
  2. return new Proxy(target, {
  3. get(target, prop) {
  4. console.log(`[${name}] Getting ${prop}`);
  5. return target[prop];
  6. },
  7. set(target, prop, value) {
  8. console.log(`[${name}] Setting ${prop} = ${value}`);
  9. target[prop] = value;
  10. return true;
  11. },
  12. deleteProperty(target, prop) {
  13. console.log(`[${name}] Deleting ${prop}`);
  14. return delete target[prop];
  15. }
  16. });
  17. }

  18. const user = createLoggingProxy({
  19. name: 'John',
  20. age: 30
  21. }, 'UserObject');

  22. user.name; // [UserObject] Getting name
  23. user.age = 31; // [UserObject] Setting age = 31
  24. delete user.age; // [UserObject] Deleting age
javascript
缓存代理:
  1. function createCachingProxy(target) {
  2. const cache = new Map();
  3. return new Proxy(target, {
  4. get(target, prop) {
  5. if (cache.has(prop)) {
  6. console.log(`Cache hit for ${prop}`);
  7. return cache.get(prop);
  8. }
  9. const value = target[prop];
  10. if (typeof value === 'function') {
  11. return new Proxy(value, {
  12. apply(target, thisArg, args) {
  13. const key = `${prop}(${JSON.stringify(args)})`;
  14. if (cache.has(key)) {
  15. console.log(`Cache hit for ${key}`);
  16. return cache.get(key);
  17. }
  18. const result = target.apply(thisArg, args);
  19. cache.set(key, result);
  20. return result;
  21. }
  22. });
  23. }
  24. cache.set(prop, value);
  25. return value;
  26. }
  27. });
  28. }

  29. const calculator = createCachingProxy({
  30. add(a, b) {
  31. console.log('Computing...');
  32. return a + b;
  33. }
  34. });

  35. console.log(calculator.add(1, 2)); // Computing... 3
  36. console.log(calculator.add(1, 2)); // Cache hit for add([1,2]) 3
javascript
只读代理:
  1. function createReadOnlyProxy(target) {
  2. return new Proxy(target, {
  3. get(target, prop) {
  4. const value = target[prop];
  5. if (typeof value === 'object' && value !== null) {
  6. return createReadOnlyProxy(value);
  7. }
  8. return value;
  9. },
  10. set() {
  11. throw new Error('Cannot modify read-only object');
  12. },
  13. deleteProperty() {
  14. throw new Error('Cannot modify read-only object');
  15. },
  16. defineProperty() {
  17. throw new Error('Cannot modify read-only object');
  18. }
  19. });
  20. }

  21. const config = createReadOnlyProxy({
  22. api: {
  23. url: 'https://api.example.com',
  24. timeout: 5000
  25. }
  26. });

  27. console.log(config.api.url); // "https://api.example.com"
  28. // config.api.url = 'new-url'; // Error: Cannot modify read-only object
javascript
Vue.js 框架
21. 详细解释 Vue.js 的响应式原理。
答案解析:
Vue.js 的响应式系统是其核心特性之一,它通过数据劫持和发布订阅模式实现数据与视图的自动同步。
1. Vue 2.x 响应式原理:
Vue 2.x 使用 Object.defineProperty 实现数据劫持:
  1. // 简化版响应式实现
  2. function observe(obj) {
  3. if (typeof obj !== 'object' || obj === null) {
  4. return obj;
  5. }
  6. Object.keys(obj).forEach(key => {
  7. defineReactive(obj, key, obj[key]);
  8. });
  9. }

  10. function defineReactive(obj, key, val) {
  11. // 递归处理嵌套对象
  12. observe(val);
  13. const dep = new Dep();
  14. Object.defineProperty(obj, key, {
  15. get() {
  16. // 依赖收集
  17. if (Dep.target) {
  18. dep.depend();
  19. }
  20. return val;
  21. },
  22. set(newVal) {
  23. if (newVal === val) return;
  24. val = newVal;
  25. // 触发更新
  26. dep.notify();
  27. }
  28. });
  29. }

  30. // 发布订阅系统
  31. class Dep {
  32. constructor() {
  33. this.subscribers = new Set();
  34. }
  35. depend() {
  36. if (Dep.target) {
  37. this.subscribers.add(Dep.target);
  38. }
  39. }
  40. notify() {
  41. this.subscribers.forEach(sub => sub.update());
  42. }
  43. }

  44. // 观察者
  45. class Watcher {
  46. constructor(vm, key, callback) {
  47. this.vm = vm;
  48. this.key = key;
  49. this.callback = callback;
  50. // 触发 getter 进行依赖收集
  51. Dep.target = this;
  52. this.vm[this.key];
  53. Dep.target = null;
  54. }
  55. update() {
  56. this.callback.call(this.vm, this.vm[this.key]);
  57. }
  58. }
javascript
2. Vue 3.x 响应式原理:
Vue 3.x 使用 Proxy 实现数据劫持:
  1. // 简化版响应式实现
  2. function reactive(target) {
  3. if (typeof target !== 'object' || target === null) {
  4. return target;
  5. }
  6. const handler = {
  7. get(target, key, receiver) {
  8. // 依赖收集
  9. track(target, key);
  10. const result = Reflect.get(target, key, receiver);
  11. if (typeof result === 'object') {
  12. return reactive(result);
  13. }
  14. return result;
  15. },
  16. set(target, key, value, receiver) {
  17. const oldValue = target[key];
  18. const result = Reflect.set(target, key, value, receiver);
  19. if (oldValue !== value) {
  20. // 触发更新
  21. trigger(target, key);
  22. }
  23. return result;
  24. }
  25. };
  26. return new Proxy(target, handler);
  27. }

  28. // 依赖收集
  29. let activeEffect;
  30. const targetMap = new WeakMap();

  31. function track(target, key) {
  32. if (!activeEffect) return;
  33. let depsMap = targetMap.get(target);
  34. if (!depsMap) {
  35. targetMap.set(target, (depsMap = new Map()));
  36. }
  37. let dep = depsMap.get(key);
  38. if (!dep) {
  39. depsMap.set(key, (dep = new Set()));
  40. }
  41. dep.add(activeEffect);
  42. }

  43. // 触发更新
  44. function trigger(target, key) {
  45. const depsMap = targetMap.get(target);
  46. if (!depsMap) return;
  47. const dep = depsMap.get(key);
  48. if (dep) {
  49. dep.forEach(effect => effect());
  50. }
  51. }

  52. // 副作用函数
  53. function effect(fn) {
  54. const effectFn = () => {
  55. activeEffect = effectFn;
  56. fn();
  57. activeEffect = null;
  58. };
  59. effectFn();
  60. return effectFn;
  61. }
javascript
3. Vue 2.x vs Vue 3.x 响应式系统的区别:
实现方式:
Vue 2.x:Object.defineProperty
Vue 3.x:Proxy
优势对比:
  1. // Vue 2.x 的限制
  2. const data = {
  3. list: []
  4. };
  5. // 无法检测数组长度变化
  6. data.list.length = 2;
  7. // 无法检测对象属性的添加和删除
  8. data.newProp = 'value';

  9. // Vue 3.x 的改进
  10. const state = reactive({
  11. list: []
  12. });
  13. // 可以检测数组长度变化
  14. state.list.length = 2;
  15. // 可以检测对象属性的添加和删除
  16. state.newProp = 'value';
javascript
性能对比:
Vue 2.x:需要递归遍历对象进行劫持
Vue 3.x:惰性劫持,访问时才进行代理
实际应用示例:
简单的响应式系统:
  1. // Vue 3.x 风格的响应式实现
  2. function createReactiveStore() {
  3. const state = reactive({
  4. count: 0,
  5. todos: []
  6. });
  7. const actions = {
  8. increment() {
  9. state.count++;
  10. },
  11. addTodo(text) {
  12. state.todos.push({
  13. id: Date.now(),
  14. text,
  15. completed: false
  16. });
  17. },
  18. toggleTodo(id) {
  19. const todo = state.todos.find(t => t.id === id);
  20. if (todo) {
  21. todo.completed = !todo.completed;
  22. }
  23. }
  24. };
  25. return { state, actions };
  26. }

  27. const store = createReactiveStore();

  28. // 创建观察者
  29. effect(() => {
  30. console.log('Count changed:', store.state.count);
  31. });

  32. effect(() => {
  33. console.log('Todos changed:', store.state.todos.length);
  34. });

  35. // 触发更新
  36. store.actions.increment(); // 输出: Count changed: 1
  37. store.actions.addTodo('Learn Vue'); // 输出: Todos changed: 1
javascript
计算属性实现:
  1. function computed(getter) {
  2. let value;
  3. let dirty = true;
  4. const effectFn = effect(getter, {
  5. lazy: true,
  6. scheduler() {
  7. if (!dirty) {
  8. dirty = true;
  9. trigger(computedRef, 'value');
  10. }
  11. }
  12. });
  13. const computedRef = {
  14. get value() {
  15. if (dirty) {
  16. value = effectFn();
  17. dirty = false;
  18. }
  19. track(computedRef, 'value');
  20. return value;
  21. }
  22. };
  23. return computedRef;
  24. }

  25. // 使用示例
  26. const state = reactive({
  27. count: 0
  28. });

  29. const double = computed(() => state.count * 2);

  30. effect(() => {
  31. console.log('Double:', double.value);
  32. });

  33. state.count++; // 输出: Double: 2
javascript
监听器实现:
  1. function watch(source, callback) {
  2. let oldValue;
  3. const getter = typeof source === 'function'
  4. ? source
  5. : () => traverse(source);
  6. const effectFn = effect(getter, {
  7. lazy: true,
  8. scheduler() {
  9. const newValue = effectFn();
  10. callback(newValue, oldValue);
  11. oldValue = newValue;
  12. }
  13. });
  14. oldValue = effectFn();
  15. }

  16. // 深度遍历对象
  17. function traverse(value, seen = new Set()) {
  18. if (typeof value !== 'object' || value === null || seen.has(value)) {
  19. return value;
  20. }
  21. seen.add(value);
  22. if (Array.isArray(value)) {
  23. for (let i = 0; i < value.length; i++) {
  24. traverse(value[i], seen);
  25. }
  26. } else {
  27. for (const key of Object.keys(value)) {
  28. traverse(value[key], seen);
  29. }
  30. }
  31. return value;
  32. }

  33. // 使用示例
  34. const state = reactive({
  35. user: {
  36. name: 'John',
  37. age: 30
  38. }
  39. });

  40. watch(
  41. () => state.user,
  42. (newValue, oldValue) => {
  43. console.log('User changed:', newValue, oldValue);
  44. }
  45. );

  46. state.user.age = 31; // 输出: User changed: { name: 'John', age: 31 } { name: 'John', age: 30 }
javascript
22. 详细解释 Vue.js 的生命周期。
答案解析:
Vue.js 的生命周期包含了组件从创建到销毁的整个过程,每个阶段都有对应的钩子函数。
1. Vue 2.x 生命周期:
  1. export default {
  2. // 组件实例创建之前
  3. beforeCreate() {
  4. // 此时无法访问 data 和 methods
  5. console.log('beforeCreate');
  6. },
  7. // 组件实例创建完成
  8. created() {
  9. // 可以访问 data 和 methods,但还未挂载到 DOM
  10. console.log('created');
  11. this.fetchData();
  12. },
  13. // 组件挂载之前
  14. beforeMount() {
  15. // 模板编译完成,但还未渲染到 DOM
  16. console.log('beforeMount');
  17. },
  18. // 组件挂载完成
  19. mounted() {
  20. // 可以访问 DOM 元素
  21. console.log('mounted');
  22. this.initChart();
  23. },
  24. // 数据更新前
  25. beforeUpdate() {
  26. // 可以在更新前访问现有的 DOM
  27. console.log('beforeUpdate');
  28. },
  29. // 数据更新后
  30. updated() {
  31. // DOM 已经更新完成
  32. console.log('updated');
  33. },
  34. // 组件销毁前
  35. beforeDestroy() {
  36. // 清理定时器、事件监听器等
  37. console.log('beforeDestroy');
  38. this.cleanup();
  39. },
  40. // 组件销毁后
  41. destroyed() {
  42. // 组件完全销毁
  43. console.log('destroyed');
  44. }
  45. }
javascript
2. Vue 3.x 生命周期:
  1. import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';

  2. export default {
  3. setup() {
  4. // 组件实例创建之前
  5. onBeforeMount(() => {
  6. console.log('onBeforeMount');
  7. });
  8. // 组件挂载完成
  9. onMounted(() => {
  10. console.log('onMounted');
  11. });
  12. // 数据更新前
  13. onBeforeUpdate(() => {
  14. console.log('onBeforeUpdate');
  15. });
  16. // 数据更新后
  17. onUpdated(() => {
  18. console.log('onUpdated');
  19. });
  20. // 组件销毁前
  21. onBeforeUnmount(() => {
  22. console.log('onBeforeUnmount');
  23. });
  24. // 组件销毁后
  25. onUnmounted(() => {
  26. console.log('onUnmounted');
  27. });
  28. }
  29. }
javascript
3. 生命周期最佳实践:
初始化数据:
  1. export default {
  2. data() {
  3. return {
  4. loading: false,
  5. data: null,
  6. error: null
  7. };
  8. },
  9. async created() {
  10. try {
  11. this.loading = true;
  12. this.data = await this.fetchData();
  13. } catch (error) {
  14. this.error = error;
  15. } finally {
  16. this.loading = false;
  17. }
  18. }
  19. }
javascript
DOM 操作和第三方库集成:
  1. export default {
  2. data() {
  3. return {
  4. chart: null
  5. };
  6. },
  7. mounted() {
  8. this.initChart();
  9. window.addEventListener('resize', this.handleResize);
  10. },
  11. beforeDestroy() {
  12. if (this.chart) {
  13. this.chart.dispose();
  14. }
  15. window.removeEventListener('resize', this.handleResize);
  16. },
  17. methods: {
  18. initChart() {
  19. this.chart = echarts.init(this.$refs.chart);
  20. this.updateChart();
  21. },
  22. handleResize() {
  23. if (this.chart) {
  24. this.chart.resize();
  25. }
  26. }
  27. }
  28. }
javascript
数据监听和缓存:
  1. export default {
  2. data() {
  3. return {
  4. searchQuery: '',
  5. debounceTimer: null
  6. };
  7. },
  8. watch: {
  9. searchQuery(newVal) {
  10. if (this.debounceTimer) {
  11. clearTimeout(this.debounceTimer);
  12. }
  13. this.debounceTimer = setTimeout(() => {
  14. this.search(newVal);
  15. }, 300);
  16. }
  17. },
  18. beforeDestroy() {
  19. if (this.debounceTimer) {
  20. clearTimeout(this.debounceTimer);
  21. }
  22. }
  23. }
javascript
实际应用示例:
数据加载组件:
  1. // DataLoader.vue
  2. export default {
  3. props: {
  4. fetchData: {
  5. type: Function,
  6. required: true
  7. }
  8. },
  9. data() {
  10. return {
  11. loading: false,
  12. data: null,
  13. error: null,
  14. retryCount: 0
  15. };
  16. },
  17. created() {
  18. this.loadData();
  19. },
  20. methods: {
  21. async loadData() {
  22. this.loading = true;
  23. this.error = null;
  24. try {
  25. this.data = await this.fetchData();
  26. } catch (error) {
  27. this.error = error;
  28. if (this.retryCount < 3) {
  29. this.retryCount++;
  30. setTimeout(() => {
  31. this.loadData();
  32. }, 1000 * this.retryCount);
  33. }
  34. } finally {
  35. this.loading = false;
  36. }
  37. }
  38. },
  39. render() {
  40. return this.$scopedSlots.default({
  41. loading: this.loading,
  42. data: this.data,
  43. error: this.error,
  44. retry: this.loadData
  45. });
  46. }
  47. }
javascript
图表组件:
  1. // ChartComponent.vue
  2. export default {
  3. props: {
  4. data: {
  5. type: Array,
  6. required: true
  7. },
  8. options: {
  9. type: Object,
  10. default: () => ({})
  11. }
  12. },
  13. data() {
  14. return {
  15. chart: null,
  16. resizeObserver: null
  17. };
  18. },
  19. mounted() {
  20. this.initChart();
  21. this.initResizeObserver();
  22. },
  23. beforeDestroy() {
  24. this.cleanup();
  25. },
  26. methods: {
  27. initChart() {
  28. this.chart = echarts.init(this.$refs.chart);
  29. this.updateChart();
  30. },
  31. updateChart() {
  32. if (!this.chart) return;
  33. const options = {
  34. ...this.defaultOptions,
  35. ...this.options,
  36. series: this.data
  37. };
  38. this.chart.setOption(options);
  39. },
  40. initResizeObserver() {
  41. this.resizeObserver = new ResizeObserver(() => {
  42. if (this.chart) {
  43. this.chart.resize();
  44. }
  45. });
  46. this.resizeObserver.observe(this.$refs.chart);
  47. },
  48. cleanup() {
  49. if (this.chart) {
  50. this.chart.dispose();
  51. this.chart = null;
  52. }
  53. if (this.resizeObserver) {
  54. this.resizeObserver.disconnect();
  55. this.resizeObserver = null;
  56. }
  57. }
  58. },
  59. watch: {
  60. data: {
  61. handler: 'updateChart',
  62. deep: true
  63. },
  64. options: {
  65. handler: 'updateChart',
  66. deep: true
  67. }
  68. }
  69. }
javascript
表单组件:
  1. // FormComponent.vue
  2. export default {
  3. data() {
  4. return {
  5. form: this.initForm(),
  6. validators: {},
  7. touched: {},
  8. errors: {}
  9. };
  10. },
  11. created() {
  12. this.initValidators();
  13. },
  14. beforeDestroy() {
  15. // 保存草稿或清理
  16. this.saveDraft();
  17. },
  18. methods: {
  19. initForm() {
  20. return {
  21. // 初始化表单数据
  22. };
  23. },
  24. initValidators() {
  25. // 设置验证规则
  26. },
  27. validate() {
  28. // 执行验证
  29. },
  30. saveDraft() {
  31. localStorage.setItem('formDraft', JSON.stringify(this.form));
  32. },
  33. async submit() {
  34. if (!this.validate()) return;
  35. try {
  36. await this.submitForm(this.form);
  37. this.$emit('success');
  38. } catch (error) {
  39. this.$emit('error', error);
  40. }
  41. }
  42. },
  43. watch: {
  44. form: {
  45. handler(newVal) {
  46. // 自动保存
  47. this.saveDraft();
  48. // 自动验证
  49. this.validate();
  50. },
  51. deep: true
  52. }
  53. }
  54. }
javascript
23. 详细解释 Vue.js 的组件通信方式。
答案解析:
Vue.js 提供了多种组件间通信的方式,每种方式都有其适用场景。
1. Props Events:
父子组件最基本的通信方式:
  1. // 父组件
  2. <template>
  3. <child-component
  4. :message="message"
  5. @update="handleUpdate"
  6. />
  7. template>

  8. <script>
  9. export default {
  10. data() {
  11. return {
  12. message: 'Hello'
  13. };
  14. },
  15. methods: {
  16. handleUpdate(value) {
  17. console.log('Received:', value);
  18. }
  19. }
  20. };
  21. script>

  22. // 子组件
  23. <template>
  24. <div>
  25. <p>{{ message }}p>
  26. <button @click="sendUpdate">Updatebutton>
  27. div>
  28. template>

  29. <script>
  30. export default {
  31. props: {
  32. message: {
  33. type: String,
  34. required: true
  35. }
  36. },
  37. methods: {
  38. sendUpdate() {
  39. this.$emit('update', 'New value');
  40. }
  41. }
  42. };
  43. script>
javascript
2. Provide/Inject:
跨多级组件传递数据:
  1. // 根组件
  2. export default {
  3. provide() {
  4. return {
  5. theme: this.theme,
  6. updateTheme: this.updateTheme
  7. };
  8. },
  9. data() {
  10. return {
  11. theme: 'light'
  12. };
  13. },
  14. methods: {
  15. updateTheme(newTheme) {
  16. this.theme = newTheme;
  17. }
  18. }
  19. };

  20. // 深层子组件
  21. export default {
  22. inject: ['theme', 'updateTheme'],
  23. methods: {
  24. toggleTheme() {
  25. this.updateTheme(this.theme === 'light' ? 'dark' : 'light');
  26. }
  27. }
  28. };
javascript
3. EventBus:
非父子组件间的通信:
  1. // eventBus.js
  2. import Vue from 'vue';
  3. export const eventBus = new Vue();

  4. // 组件 A
  5. import { eventBus } from './eventBus';

  6. export default {
  7. methods: {
  8. sendMessage() {
  9. eventBus.$emit('message', 'Hello from A');
  10. }
  11. }
  12. };

  13. // 组件 B
  14. import { eventBus } from './eventBus';

  15. export default {
  16. created() {
  17. eventBus.$on('message', this.handleMessage);
  18. },
  19. beforeDestroy() {
  20. eventBus.$off('message', this.handleMessage);
  21. },
  22. methods: {
  23. handleMessage(msg) {
  24. console.log(msg);
  25. }
  26. }
  27. };
javascript
4. Vuex:
全局状态管理:
  1. // store.js
  2. import Vue from 'vue';
  3. import Vuex from 'vuex';

  4. Vue.use(Vuex);

  5. export default new Vuex.Store({
  6. state: {
  7. count: 0,
  8. todos: []
  9. },
  10. mutations: {
  11. INCREMENT(state) {
  12. state.count++;
  13. },
  14. ADD_TODO(state, todo) {
  15. state.todos.push(todo);
  16. }
  17. },
  18. actions: {
  19. async fetchTodos({ commit }) {
  20. const todos = await api.getTodos();
  21. todos.forEach(todo => commit('ADD_TODO', todo));
  22. }
  23. },
  24. getters: {
  25. completedTodos: state => state.todos.filter(todo => todo.completed)
  26. }
  27. });

  28. // 组件中使用
  29. export default {
  30. computed: {
  31. ...mapState(['count']),
  32. ...mapGetters(['completedTodos'])
  33. },
  34. methods: {
  35. ...mapMutations(['INCREMENT']),
  36. ...mapActions(['fetchTodos'])
  37. }
  38. };
javascript
5. $refs $parent/$children:
直接访问组件实例:
  1. // 父组件
  2. <template>
  3. <div>
  4. <child-component ref="child" />
  5. <button @click="callChildMethod">Call Childbutton>
  6. div>
  7. template>

  8. <script>
  9. export default {
  10. methods: {
  11. callChildMethod() {
  12. this.$refs.child.someMethod();
  13. }
  14. }
  15. };
  16. script>

  17. // 子组件
  18. export default {
  19. methods: {
  20. someMethod() {
  21. console.log('Called from parent');
  22. },
  23. callParentMethod() {
  24. this.$parent.parentMethod();
  25. }
  26. }
  27. };
javascript
实际应用示例:
表单组件通信:
  1. // FormContainer.vue
  2. <template>
  3. <div>
  4. <form-item
  5. v-for="(field, index) in fields"
  6. :key="index"
  7. v-model="formData[field.name]"
  8. :field="field"
  9. @validate="handleValidate"
  10. />
  11. <button @click="submit">Submitbutton>
  12. div>
  13. template>

  14. <script>
  15. export default {
  16. provide() {
  17. return {
  18. form: this
  19. };
  20. },
  21. data() {
  22. return {
  23. formData: {},
  24. validationResults: {}
  25. };
  26. },
  27. methods: {
  28. handleValidate(fieldName, isValid, error) {
  29. this.validationResults[fieldName] = { isValid, error };
  30. },
  31. async submit() {
  32. if (Object.values(this.validationResults).every(r => r.isValid)) {
  33. await this.submitForm(this.formData);
  34. }
  35. }
  36. }
  37. };
  38. script>

  39. // FormItem.vue
  40. <template>
  41. <div class="form-item">
  42. <label>{{ field.label }}label>
  43. <input
  44. :value="value"
  45. @input="handleInput"
  46. @blur="validate"
  47. />
  48. <span class="error" v-if="error">{{ error }}span>
  49. div>
  50. template>

  51. <script>
  52. export default {
  53. inject: ['form'],
  54. props: ['value', 'field'],
  55. data() {
  56. return {
  57. error: null
  58. };
  59. },
  60. methods: {
  61. handleInput(e) {
  62. this.$emit('input', e.target.value);
  63. this.validate();
  64. },
  65. validate() {
  66. const value = this.value;
  67. const rules = this.field.rules;
  68. let isValid = true;
  69. let error = null;
  70. // 执行验证
  71. if (rules.required && !value) {
  72. isValid = false;
  73. error = `${this.field.label} is required`;
  74. }
  75. this.error = error;
  76. this.$emit('validate', this.field.name, isValid, error);
  77. }
  78. }
  79. };
  80. script>
javascript
多级菜单组件:
  1. // Menu.vue
  2. <template>
  3. <div class="menu">
  4. <menu-item
  5. v-for="item in items"
  6. :key="item.id"
  7. :item="item"
  8. />
  9. div>
  10. template>

  11. <script>
  12. export default {
  13. provide() {
  14. return {
  15. rootMenu: this
  16. };
  17. },
  18. data() {
  19. return {
  20. activeItem: null
  21. };
  22. },
  23. methods: {
  24. setActiveItem(item) {
  25. this.activeItem = item;
  26. }
  27. }
  28. };
  29. script>

  30. // MenuItem.vue
  31. <template>
  32. <div
  33. class="menu-item"
  34. :class="{ active: isActive }"
  35. @click="handleClick"
  36. >
  37. {{ item.label }}
  38. <div v-if="item.children" class="submenu">
  39. <menu-item
  40. v-for="child in item.children"
  41. :key="child.id"
  42. :item="child"
  43. />
  44. div>
  45. div>
  46. template>

  47. <script>
  48. export default {
  49. name: 'MenuItem',
  50. inject: ['rootMenu'],
  51. props: ['item'],
  52. computed: {
  53. isActive() {
  54. return this.rootMenu.activeItem === this.item;
  55. }
  56. },
  57. methods: {
  58. handleClick() {
  59. this.rootMenu.setActiveItem(this.item);
  60. if (this.item.onClick) {
  61. this.item.onClick();
  62. }
  63. }
  64. }
  65. };
  66. script>
javascript
全局消息通知:
  1. // messagePlugin.js
  2. let messageInstance = null;

  3. export default {
  4. install(Vue) {
  5. Vue.prototype.$message = this.showMessage;
  6. },
  7. showMessage({ type = 'info', message, duration = 3000 }) {
  8. if (!messageInstance) {
  9. const MessageConstructor = Vue.extend({
  10. render(h) {
  11. return h('div', {
  12. class: ['message', `message-${type}`]
  13. }, message);
  14. }
  15. });
  16. messageInstance = new MessageConstructor();
  17. const vm = messageInstance.$mount();
  18. document.body.appendChild(vm.$el);
  19. setTimeout(() => {
  20. document.body.removeChild(vm.$el);
  21. messageInstance = null;
  22. }, duration);
  23. }
  24. }
  25. };

  26. // 使用示例
  27. this.$message({
  28. type: 'success',
  29. message: 'Operation successful'
  30. });
javascript
24. 详细解释 Vue.js 的自定义指令。
答案解析:
Vue.js 的自定义指令用于对底层 DOM 元素进行直接操作,当内置指令无法满足需求时非常有用。
1. 指令定义:
  1. // 全局指令
  2. Vue.directive('focus', {
  3. // 指令绑定到元素时调用
  4. bind(el, binding, vnode) {
  5. // 进行初始化设置
  6. },
  7. // 被绑定元素插入父节点时调用
  8. inserted(el, binding, vnode) {
  9. el.focus();
  10. },
  11. // 组件更新时调用
  12. update(el, binding, vnode, oldVnode) {
  13. // 根据值的变化进行更新
  14. },
  15. // 组件更新完成后调用
  16. componentUpdated(el, binding, vnode, oldVnode) {
  17. // 组件和子组件更新完成后进行操作
  18. },
  19. // 指令与元素解绑时调用
  20. unbind(el, binding, vnode) {
  21. // 进行清理工作
  22. }
  23. });

  24. // 局部指令
  25. export default {
  26. directives: {
  27. focus: {
  28. inserted(el) {
  29. el.focus();
  30. }
  31. }
  32. }
  33. };
javascript
2. 指令钩子函数参数:
  1. Vue.directive('example', {
  2. bind(el, binding, vnode) {
  3. // el: 指令绑定的元素
  4. // binding: 指令的详细信息
  5. // - name: 指令名
  6. // - value: 指令的值
  7. // - oldValue: 指令前一个值
  8. // - expression: 指令表达式
  9. // - arg: 指令参数
  10. // - modifiers: 指令修饰符
  11. // vnode: Vue 编译生成的虚拟节点
  12. console.log(binding.value); // 指令值
  13. console.log(binding.arg); // 指令参数
  14. console.log(binding.modifiers); // 指令修饰符
  15. }
  16. });
javascript
3. 实际应用示例:
点击外部关闭指令:
  1. Vue.directive('click-outside', {
  2. bind(el, binding) {
  3. el.clickOutsideHandler = (event) => {
  4. if (!(el === event.target || el.contains(event.target))) {
  5. binding.value(event);
  6. }
  7. };
  8. document.addEventListener('click', el.clickOutsideHandler);
  9. },
  10. unbind(el) {
  11. document.removeEventListener('click', el.clickOutsideHandler);
  12. }
  13. });

  14. // 使用示例
  15. <template>
  16. <div v-click-outside="closeDropdown">
  17. div>
  18. template>
javascript
图片懒加载指令:
  1. Vue.directive('lazy', {
  2. bind(el, binding) {
  3. const observer = new IntersectionObserver(entries => {
  4. entries.forEach(entry => {
  5. if (entry.isIntersecting) {
  6. el.src = binding.value;
  7. observer.unobserve(el);
  8. }
  9. });
  10. });
  11. observer.observe(el);
  12. }
  13. });

  14. // 使用示例
  15. <template>
  16. <img v-lazy="imageUrl" />
  17. template>
javascript
权限控制指令:
  1. Vue.directive('permission', {
  2. bind(el, binding) {
  3. const { value } = binding;
  4. const userRoles = store.state.user.roles;
  5. if (!userRoles.some(role => value.includes(role))) {
  6. el.parentNode.removeChild(el);
  7. }
  8. }
  9. });

  10. // 使用示例
  11. <template>
  12. <button v-permission="['admin', 'editor']">
  13. Delete
  14. button>
  15. template>
javascript
输入限制指令:
  1. Vue.directive('number-only', {
  2. bind(el) {
  3. el.handler = function(e) {
  4. e = e || window.event;
  5. const charCode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
  6. const re = /\d/;
  7. if (!re.test(String.fromCharCode(charCode)) && charCode > 9) {
  8. if (e.preventDefault) {
  9. e.preventDefault();
  10. } else {
  11. e.returnValue = false;
  12. }
  13. }
  14. };
  15. el.addEventListener('keypress', el.handler);
  16. },
  17. unbind(el) {
  18. el.removeEventListener('keypress', el.handler);
  19. }
  20. });

  21. // 使用示例
  22. <template>
  23. <input v-number-only v-model="value" />
  24. template>
javascript
元素拖拽指令:
  1. Vue.directive('draggable', {
  2. bind(el) {
  3. el.style.position = 'absolute';
  4. el.draggable = true;
  5. let startX, startY, initialX, initialY;
  6. function dragStart(e) {
  7. startX = e.clientX - initialX;
  8. startY = e.clientY - initialY;
  9. document.addEventListener('mousemove', drag);
  10. document.addEventListener('mouseup', dragEnd);
  11. }
  12. function drag(e) {
  13. e.preventDefault();
  14. const x = e.clientX - startX;
  15. const y = e.clientY - startY;
  16. el.style.left = `${x}px`;
  17. el.style.top = `${y}px`;
  18. }
  19. function dragEnd() {
  20. initialX = el.offsetLeft;
  21. initialY = el.offsetTop;
  22. document.removeEventListener('mousemove', drag);
  23. document.removeEventListener('mouseup', dragEnd);
  24. }
  25. el.addEventListener('mousedown', dragStart);
  26. }
  27. });

  28. // 使用示例
  29. <template>
  30. <div v-draggable class="draggable-element">
  31. Drag me!
  32. div>
  33. template>
javascript
25. 详细解释 Vue.js 的插件系统。
答案解析:
Vue.js 的插件系统允许我们为 Vue 添加全局功能,包括全局方法、指令、过滤器等。
1. 插件开发:
  1. // myPlugin.js
  2. export default {
  3. install(Vue, options = {}) {
  4. // 1. 添加全局方法或属性
  5. Vue.myGlobalMethod = function() {
  6. // 全局方法实现
  7. };
  8. // 2. 添加全局指令
  9. Vue.directive('my-directive', {
  10. bind(el, binding) {
  11. // 指令实现
  12. }
  13. });
  14. // 3. 添加实例方法
  15. Vue.prototype.$myMethod = function() {
  16. // 实例方法实现
  17. };
  18. // 4. 添加全局混入
  19. Vue.mixin({
  20. created() {
  21. // 混入逻辑
  22. }
  23. });
  24. // 5. 添加全局组件
  25. Vue.component('my-component', {
  26. // 组件选项
  27. });
  28. }
  29. };

  30. // 使用插件
  31. import MyPlugin from './myPlugin';
  32. Vue.use(MyPlugin, { /* 选项 */ });
javascript
2. 实际应用示例:
状态管理插件:
  1. // store.js
  2. class Store {
  3. constructor(options = {}) {
  4. this.state = Vue.observable(options.state || {});
  5. this.mutations = options.mutations || {};
  6. this.actions = options.actions || {};
  7. }
  8. commit(type, payload) {
  9. if (!this.mutations[type]) {
  10. throw new Error(`Unknown mutation type: ${type}`);
  11. }
  12. this.mutations[type](this.state, payload);
  13. }
  14. dispatch(type, payload) {
  15. if (!this.actions[type]) {
  16. throw new Error(`Unknown action type: ${type}`);
  17. }
  18. return this.actions[type]({
  19. state: this.state,
  20. commit: this.commit.bind(this)
  21. }, payload);
  22. }
  23. }

  24. export default {
  25. install(Vue) {
  26. Vue.prototype.$store = new Store({
  27. state: {
  28. count: 0
  29. },
  30. mutations: {
  31. INCREMENT(state) {
  32. state.count++;
  33. }
  34. },
  35. actions: {
  36. increment({ commit }) {
  37. commit('INCREMENT');
  38. }
  39. }
  40. });
  41. }
  42. };
javascript
API 请求插件:
  1. // api.js
  2. class ApiClient {
  3. constructor(baseURL) {
  4. this.baseURL = baseURL;
  5. }
  6. async request(method, endpoint, data = null) {
  7. const options = {
  8. method,
  9. headers: {
  10. 'Content-Type': 'application/json'
  11. }
  12. };
  13. if (data) {
  14. options.body = JSON.stringify(data);
  15. }
  16. const response = await fetch(`${this.baseURL}${endpoint}`, options);
  17. if (!response.ok) {
  18. throw new Error(`HTTP error! status: ${response.status}`);
  19. }
  20. return response.json();
  21. }
  22. get(endpoint) {
  23. return this.request('GET', endpoint);
  24. }
  25. post(endpoint, data) {
  26. return this.request('POST', endpoint, data);
  27. }
  28. put(endpoint, data) {
  29. return this.request('PUT', endpoint, data);
  30. }
  31. delete(endpoint) {
  32. return this.request('DELETE', endpoint);
  33. }
  34. }

  35. export default {
  36. install(Vue, options = {}) {
  37. const api = new ApiClient(options.baseURL || '');
  38. Vue.prototype.$api = api;
  39. }
  40. };
javascript
国际化插件:
  1. // i18n.js
  2. class I18n {
  3. constructor(options = {}) {
  4. this.locale = options.locale || 'en';
  5. this.messages = options.messages || {};
  6. }
  7. setLocale(locale) {
  8. this.locale = locale;
  9. }
  10. t(key, params = {}) {
  11. const message = this.messages[this.locale]?.[key] || key;
  12. return message.replace(/\{(\w+)\}/g, (_, key) => params[key]);
  13. }
  14. }

  15. export default {
  16. install(Vue, options = {}) {
  17. const i18n = new I18n(options);
  18. Vue.prototype.$t = function(key, params) {
  19. return i18n.t(key, params);
  20. };
  21. Vue.prototype.$i18n = i18n;
  22. Vue.directive('t', {
  23. bind(el, binding) {
  24. el.textContent = i18n.t(binding.value);
  25. },
  26. update(el, binding) {
  27. el.textContent = i18n.t(binding.value);
  28. }
  29. });
  30. }
  31. };

  32. // 使用示例
  33. Vue.use(i18nPlugin, {
  34. locale: 'en',
  35. messages: {
  36. en: {
  37. hello: 'Hello {name}!',
  38. welcome: 'Welcome to our app'
  39. },
  40. zh: {
  41. hello: '你好 {name}!',
  42. welcome: '欢迎使用我们的应用'
  43. }
  44. }
  45. });
javascript
表单验证插件:
  1. // validator.js
  2. class Validator {
  3. constructor() {
  4. this.rules = {
  5. required: value => !!value || '此字段是必填的',
  6. email: value => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || '请输入有效的邮箱地址',
  7. minLength: min => value => value.length >= min || `最少需要 ${min} 个字符`,
  8. maxLength: max => value => value.length <= max || `最多允许 ${max} 个字符`
  9. };
  10. }
  11. validate(value, rules) {
  12. for (const rule of rules) {
  13. if (typeof rule === 'string') {
  14. const result = this.rules[rule](value);
  15. if (result !== true) return result;
  16. } else if (typeof rule === 'function') {
  17. const result = rule(value);
  18. if (result !== true) return result;
  19. }
  20. }
  21. return true;
  22. }
  23. addRule(name, validator) {
  24. this.rules[name] = validator;
  25. }
  26. }

  27. export default {
  28. install(Vue) {
  29. const validator = new Validator();
  30. Vue.prototype.$validator = validator;
  31. Vue.directive('validate', {
  32. bind(el, binding, vnode) {
  33. const rules = binding.value;
  34. const inputElement = el.tagName === 'INPUT' ? el : el.querySelector('input');
  35. inputElement.addEventListener('input', () => {
  36. const result = validator.validate(inputElement.value, rules);
  37. if (result !== true) {
  38. vnode.context.$emit('validation-error', result);
  39. } else {
  40. vnode.context.$emit('validation-success');
  41. }
  42. });
  43. }
  44. });
  45. }
  46. };

  47. // 使用示例
  48. <template>
  49. <div>
  50. <input
  51. v-validate="['required', 'email']"
  52. v-model="email"
  53. @validation-error="handleError"
  54. />
  55. <span class="error" v-if="error">{{ error }}span>
  56. div>
  57. template>

  58. <script>
  59. export default {
  60. data() {
  61. return {
  62. email: '',
  63. error: null
  64. };
  65. },
  66. methods: {
  67. handleError(error) {
  68. this.error = error;
  69. }
  70. }
  71. };
  72. script>
javascript
26. 详细解释 Vue.js 的虚拟 DOM 和渲染机制。
答案解析:
Vue.js 使用虚拟 DOM(Virtual DOM)来提高渲染性能,它是对真实 DOM 的一种抽象表示。
1. 虚拟 DOM 的实现:
  1. // VNode 类
  2. class VNode {
  3. constructor(tag, data, children, text) {
  4. this.tag = tag; // 标签名
  5. this.data = data; // 属性、事件等数据
  6. this.children = children; // 子节点
  7. this.text = text; // 文本内容
  8. }
  9. }

  10. // 创建虚拟节点
  11. function createElement(tag, data = {}, ...children) {
  12. if (typeof tag === 'string') {
  13. return new VNode(tag, data, children);
  14. } else {
  15. // 组件 VNode
  16. return new VNode(
  17. 'component',
  18. { ...data, component: tag },
  19. children
  20. );
  21. }
  22. }

  23. // 渲染函数示例
  24. function render() {
  25. return createElement('div', { class: 'container' },
  26. createElement('h1', { style: { color: 'red' } }, 'Hello'),
  27. createElement('p', null, 'This is a paragraph')
  28. );
  29. }
javascript
2. Diff 算法:
  1. function patch(oldVNode, newVNode) {
  2. // 1. 如果新节点不存在
  3. if (!newVNode) {
  4. return oldVNode.el.parentNode.removeChild(oldVNode.el);
  5. }
  6. // 2. 如果是相同节点
  7. if (sameVNode(oldVNode, newVNode)) {
  8. patchVNode(oldVNode, newVNode);
  9. } else {
  10. // 3. 不同节点,直接替换
  11. const oldEl = oldVNode.el;
  12. const parentEl = oldEl.parentNode;
  13. // 创建新元素
  14. createElm(newVNode);
  15. if (parentEl) {
  16. parentEl.replaceChild(newVNode.el, oldEl);
  17. }
  18. }
  19. }

  20. function sameVNode(oldVNode, newVNode) {
  21. return oldVNode.key === newVNode.key && oldVNode.tag === newVNode.tag;
  22. }

  23. function patchVNode(oldVNode, newVNode) {
  24. const el = newVNode.el = oldVNode.el;
  25. const oldCh = oldVNode.children;
  26. const newCh = newVNode.children;
  27. // 1. 文本节点
  28. if (typeof newVNode.text !== 'undefined') {
  29. if (newVNode.text !== oldVNode.text) {
  30. el.textContent = newVNode.text;
  31. }
  32. return;
  33. }
  34. // 2. 更新属性
  35. updateProperties(newVNode, oldVNode.data);
  36. // 3. 更新子节点
  37. if (oldCh && newCh) {
  38. updateChildren(el, oldCh, newCh);
  39. } else if (newCh) {
  40. // 只有新子节点
  41. for (let i = 0; i < newCh.length; i++) {
  42. el.appendChild(createElm(newCh[i]));
  43. }
  44. } else if (oldCh) {
  45. // 只有旧子节点
  46. el.innerHTML = '';
  47. }
  48. }

  49. function updateChildren(parentEl, oldCh, newCh) {
  50. let oldStartIdx = 0;
  51. let oldEndIdx = oldCh.length - 1;
  52. let newStartIdx = 0;
  53. let newEndIdx = newCh.length - 1;
  54. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  55. if (sameVNode(oldCh[oldStartIdx], newCh[newStartIdx])) {
  56. // 从头比较
  57. patchVNode(oldCh[oldStartIdx], newCh[newStartIdx]);
  58. oldStartIdx++;
  59. newStartIdx++;
  60. } else if (sameVNode(oldCh[oldEndIdx], newCh[newEndIdx])) {
  61. // 从尾比较
  62. patchVNode(oldCh[oldEndIdx], newCh[newEndIdx]);
  63. oldEndIdx--;
  64. newEndIdx--;
  65. } else {
  66. // 需要移动节点
  67. // ... 其他 diff 策略
  68. }
  69. }
  70. // 处理剩余节点
  71. if (oldStartIdx > oldEndIdx) {
  72. // 添加新节点
  73. for (let i = newStartIdx; i <= newEndIdx; i++) {
  74. parentEl.appendChild(createElm(newCh[i]));
  75. }
  76. } else if (newStartIdx > newEndIdx) {
  77. // 删除多余节点
  78. for (let i = oldStartIdx; i <= oldEndIdx; i++) {
  79. parentEl.removeChild(oldCh[i].el);
  80. }
  81. }
  82. }
javascript
3. 模板编译:
  1. // 模板编译过程
  2. function compile(template) {
  3. // 1. 解析模板
  4. const ast = parse(template);
  5. // 2. 优化静态节点
  6. optimize(ast);
  7. // 3. 生成代码
  8. const code = generate(ast);
  9. // 4. 创建渲染函数
  10. return new Function(`with(this){return ${code}}`);
  11. }

  12. // 解析模板
  13. function parse(template) {
  14. const stack = [];
  15. let currentParent;
  16. let root;
  17. parseHTML(template, {
  18. start(tag, attrs, unary) {
  19. const element = {
  20. type: 1,
  21. tag,
  22. attrsList: attrs,
  23. parent: currentParent,
  24. children: []
  25. };
  26. if (!root) {
  27. root = element;
  28. }
  29. if (currentParent) {
  30. currentParent.children.push(element);
  31. }
  32. if (!unary) {
  33. currentParent = element;
  34. stack.push(element);
  35. }
  36. },
  37. end() {
  38. stack.pop();
  39. currentParent = stack[stack.length - 1];
  40. },
  41. chars(text) {
  42. if (!currentParent) return;
  43. const children = currentParent.children;
  44. if (text.trim()) {
  45. children.push({
  46. type: 3,
  47. text
  48. });
  49. }
  50. }
  51. });
  52. return root;
  53. }

  54. // 优化静态节点
  55. function optimize(root) {
  56. // 1. 标记静态节点
  57. markStatic(root);
  58. // 2. 标记静态根节点
  59. markStaticRoots(root);
  60. }

  61. function markStatic(node) {
  62. node.static = isStatic(node);
  63. if (node.type === 1) {
  64. for (let i = 0; i < node.children.length; i++) {
  65. const child = node.children[i];
  66. markStatic(child);
  67. if (!child.static) {
  68. node.static = false;
  69. }
  70. }
  71. }
  72. }

  73. function isStatic(node) {
  74. if (node.type === 2) { // 表达式
  75. return false;
  76. }
  77. if (node.type === 3) { // 文本
  78. return true;
  79. }
  80. return !node.if && !node.for; // 元素
  81. }

  82. // 生成代码
  83. function generate(ast) {
  84. const code = genElement(ast);
  85. return `{render:function(){${code}}}`;
  86. }

  87. function genElement(el) {
  88. if (el.static) {
  89. return `_m(${el.staticIndex})`;
  90. }
  91. let code;
  92. const data = genData(el);
  93. const children = genChildren(el);
  94. code = `_c('${el.tag}'${
  95. data ? `,${data}` : ''
  96. }${
  97. children ? `,${children}` : ''
  98. })`;
  99. return code;
  100. }
javascript
4. 实际应用示例:
渲染函数组件:
  1. // 使用渲染函数创建组件
  2. Vue.component('anchored-heading', {
  3. render: function (createElement) {
  4. return createElement(
  5. 'h' + this.level, // 标签名
  6. this.$slots.default // 子节点数组
  7. );
  8. },
  9. props: {
  10. level: {
  11. type: Number,
  12. required: true
  13. }
  14. }
  15. });

  16. // 使用示例
  17. <anchored-heading :level="1">
  18. Hello world!
  19. anchored-heading>
javascript
函数式组件:
  1. // 函数式组件
  2. Vue.component('my-component', {
  3. functional: true,
  4. props: {
  5. // 声明 props
  6. message: {
  7. type: String,
  8. required: true
  9. }
  10. },
  11. render: function (createElement, context) {
  12. // context 包含:props、children、slots、data、parent 等
  13. return createElement('div', context.props.message);
  14. }
  15. });
javascript
JSX 支持:
  1. // 使用 JSX
  2. export default {
  3. data() {
  4. return {
  5. items: ['A', 'B', 'C']
  6. };
  7. },
  8. render() {
  9. return (
  10. <div class="container">
  11. {this.items.map(item => (
  12. <div key={item} class="item">
  13. {item}
  14. div>
  15. ))}
  16. div>
  17. );
  18. }
  19. };
javascript
高阶组件:
  1. // 高阶组件工厂函数
  2. function withLog(WrappedComponent) {
  3. return {
  4. mounted() {
  5. console.log(`${WrappedComponent.name} mounted`);
  6. },
  7. props: WrappedComponent.props,
  8. render(h) {
  9. return h(WrappedComponent, {
  10. props: this.$props,
  11. on: this.$listeners
  12. });
  13. }
  14. };
  15. }

  16. // 使用高阶组件
  17. const MyComponent = {
  18. name: 'MyComponent',
  19. props: ['message'],
  20. template: '
    {{ message }}
    '
  21. };

  22. const LoggedComponent = withLog(MyComponent);
javascript
动态组件:
  1. // 动态组件工厂
  2. const AsyncComponent = () => ({
  3. // 需要加载的组件
  4. component: import('./MyComponent.vue'),
  5. // 加载中应当渲染的组件
  6. loading: LoadingComponent,
  7. // 出错时渲染的组件
  8. error: ErrorComponent,
  9. // 展示加载时组件的延时时间。默认值是 200 (毫秒)
  10. delay: 200,
  11. // 如果提供了超时时间且组件加载也超时了,
  12. // 则使用加载失败时的组件。默认值是:`Infinity`
  13. timeout: 3000
  14. });

  15. export default {
  16. components: {
  17. AsyncComponent
  18. },
  19. template: `
  20. <div>
  21. <async-component v-if="show" />
  22. <button @click="show = !show">Togglebutton>
  23. div>
  24. `,
  25. data() {
  26. return {
  27. show: false
  28. };
  29. }
  30. };
javascript