前端面试手写代码合集

185 阅读3分钟

防抖:

说明:高频操作只在最后一次执行。
原理:事件触发n秒后,再去执行回调函数,如果n秒内事件被重新触发,则重新计时。
应用场景:搜索框输入时搜索联想。

*** 
* @params fn 被防抖的函数
* @params wait 等待时间
* @params now 是否立即执行
* @params task 状态
*
function debounce(fn,wait,now){
 let task = null
 
 reture function(){
  let that = this;
  if(now){fn.apply(that,argments)}
  
  if(task){clearTimeout(task)}
 
  task = setTimeout(fn.apply(that,argments),wait)
 }
}

节流:

说明:每隔一段时间执行一次,将高频操作变为低频操作。 原理:n秒内触发的事件合并为一次执行。 应用场景:监听页面滚动,按钮频繁调用。

function throttle(fn,wait){
 let task = null
 return function(){
  if(!task){
    setTimeout(()=>{
     task = null
     fn.apply(this,argments)
    },wait)
  }
 }
}

浅拷贝:

创建一个新对象,这个对象有着原始对象属性值的一份精确拷贝。如果属性是基本类型,拷贝的就是基本类型的值。如果是引用类型,拷贝的就是引用类型的内存地址,所以修改新对象,会影响原对象。

let obj = {
 name:"1",
 age:{
  alex:"2"
 },
 arr:['1','2']
}

function clone(obj){
 let result = {} 
 for(key in obj){
   result[key] = obj[key]
 }
 return result
}
let obj2 = {}
obj2 = clone(obj)
obj2.age.alex = "3"

创建一个新的对象,遍历需要克隆的对象,将需要克隆对象的属性依次添加到新对象上,返回。

深拷贝

将一个对象从内存中完整的拷贝一份出来,在堆内存中开辟一个新的区域存放,所以修改新对象不会影响原对象。

let obj = {
 name:"1",
 age:{
  alex:"2"
 },
 arr:['1','2']
}

function clone(obj){
 if(typeof obj === 'object'){
   let result = Array.isArray(obj) ? [] : {}
   for(const key in obj){
    result[key] = clone(obj[key])
   }
   return result 
 }else{
  return obj
 }
}

let obj2 = {}
obj2 = clone(obj)
obj2.age.alex = "3"

简单理解:是否共享同一块内存

apply实现

作用:改变函数执行时的this指向
说明:挂在Function的一个方法,调用这个方法必须得是函数。(apply是以a开头的,它传给function也是a开头的,array数组)
原理:接收两个参数,** 第一个参数为函数上下文this,第二个参数为一个数组形式传入的函数参数**。

Function.prototype.myapply = function(that,args){
 // 在Function原型上扩展一个方法并接受两个参数
 
 that = that || window
 args = args ? args : []
 // 如果没有传或传的值为空对象 context指向window。args容错处理
 
 let key = Symbol()
 that[key] = this
 //给调用函数新增一个独一无二的属性以免覆盖原有属性,并绑定this
 
 let result = that[key](...args)
 delete that[key]
 return result
 // 处理返回值,并删除自定义方法。
}

call实现

原理:第二个参数,以逗号隔开逐个传入

Function.prototype.mycall = function(that,...args){
 that = that || window
 args = args ? args : []
 
 const key = Symbol()
 that[key] = this //*
 
 const result = that[key](...args)
 delect that[key]
 
 return result
}

instanceof实现

语法:object instanceof constructor
原理:判断对象的类型,返回布尔值。对象的原型链是否出现了类型的prototype 解释:

  1. 获取对象的原型链
  2. 获取类型的protype
  3. 一直循环判断对象的原型链是否等于对象的原型,直到原型对象为null,因为原型链最终为null
function myInstanceof(left,right){
 left = left.__proto__;
 let prototype = right.prototype;
 while(true){
  if(left === null || left === undefined)
   return false
  if(left === prototype)
   return true
  left = left.__proto__
 }
}

const a = "test"
myInstanceof(a,String)