前端面试手写核心 Cheat Sheet(终极精简版)

背会这一页,面试手写题直接稳过!


1. 防抖 & 节流

防抖(debounce)

  • 场景:搜索输入、窗口 resize、按钮防重复点击
  • 核心:频繁触发 → 只执行最后一次
js 复制代码
function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

节流(throttle)

  • 场景:滚动加载、高频点击、鼠标移动
  • 核心:频繁触发 → 每隔一段时间执行一次
js 复制代码
function throttle(fn, delay) {
  let lastTime = 0
  return function (...args) {
    const now = Date.now()
    if (now - lastTime >= delay) {
      fn.apply(this, args)
      lastTime = now
    }
  }
}

2. 数组去重

js 复制代码
function unique(arr) {
  return [...new Set(arr)]
}

3. call / apply / bind

myCall

js 复制代码
Function.prototype.myCall = function (context, ...args) {
  context = context || window
  const fn = Symbol()
  context[fn] = this
  const result = context[fn](...args)
  delete context[fn]
  return result
}

myApply

js 复制代码
Function.prototype.myApply = function (context, args) {
  context = context || window
  args = args || []
  const fn = Symbol()
  context[fn] = this
  const result = context[fn](...args)
  delete context[fn]
  return result
}

myBind

js 复制代码
Function.prototype.myBind = function (context) {
  const self = this
  return function (...args) {
    return self.apply(context || window, args)
  }
}

4. 深拷贝(含循环引用)

js 复制代码
function deepClone(obj, map = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  if (map.has(obj)) return map.get(obj)

  const clone = Array.isArray(obj) ? [] : {}
  map.set(obj, clone)

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key], map)
    }
  }
  return clone
}

5. this 指向口诀

  1. obj.fun() → this = obj
  2. fun() → this = window / undefined
  3. call / apply / bind → 手动指定 this
  4. new → this = 新创建的对象

6. 场景速查

  • 搜索输入联想 → 防抖
  • 滚动加载更多 → 节流
  • 按钮防重复点击 → 防抖
  • 拷贝多层对象 → 深拷贝
相关推荐
光影少年6 小时前
react navite性能优化 & 常见坑
前端·react native·掘金·金石计划
八角丶6 小时前
Node.js Cluster 详解
前端·node.js
名字还没想好☜7 小时前
React 用 useEffect 做轮询实战:setInterval 拿到旧 state 的闭包陷阱与正确清理
前端·javascript·react.js·react·useeffect
hiahiahia1237 小时前
AI Web 项目的文件到底应该怎么放?
前端·人工智能
愚公搬代码7 小时前
【愚公系列】《Web应用安全》003-测试环境的搭建
前端·安全
_codemonster7 小时前
主流前端技术分层选型
前端
犹豫的果冻布丁9 小时前
从零给 DeepSeek Harness 写一个壁纸皮肤插件(已开源)
前端·后端
漏刻有时9 小时前
数据可视化Three.js 3D 地图实战:单文件原生实现省域区县拉伸建模
前端
会说话的番茄10 小时前
AI 满嘴跑火车怎么办?给它配个"小抄"
前端·aigc
计算机魔术师10 小时前
AI 权力集中辩论实录:从「token 工厂」到「唯一幸存者」
前端