那些面试的手写

12/30/2022 面试

# 那些面试的手写

# 防抖和节流

  • 防抖:将多次高频操作优化为最后一次执行,常见场景:input 框输入,只在输入完成后才触发。防止多次提交按钮,只执行最后提交的一次
const debounce = (fn,wait) => {
  let timer = null
  return (...args) => {
    if(timer) clearTimeout(timer)
    timer = setTimeout(()=>{
      fn.apply(this,args)
    },wait)
  }
}
1
2
3
4
5
6
7
8
9
  • 节流:在一个单位时间内,只触发一次。如果这个单位时间内触发多次函数,只有一次生效。常见场景:浏览器 resize
const throttle=(fn,wait)=>{
  let flag=true
  return (...args)=>{
    if(!flag) return
    flag=flase
    setTimeout(()=>{
      fn.apply(this,args)
      flag=true
    },wait)
  }
}
1
2
3
4
5
6
7
8
9
10
11

# 手写 new 的执行过程

首先我们知道 new 的执行过程如

  1. 创建一个空对象
  2. 将对象的 __proto__ 指向构造函数的 prototype
  3. 将这个对象作为构造函数的 this
  4. 确保返回值为对象
function myNew(Con,...arg) {
  let obj=Object.creat(Con.prototype)
  let result=Con.apply(obj,arg)
  return result instanceof Object?result:obj

}

1
2
3
4
5
6
7

# 编写javascript深度克隆函数

  Object.prototype.clone = function() {
      var newObject = this.constructor === Array ? [] : {}  //对象的深拷贝 获取对应的构造函数 [] 或者 {}
      for (let e in this) { //遍历对象的属性 in  this[e]
        newObject[e] = typeof this[e] === 'object' ? this[e].clone() : this[e]  //对象中的属性如果还是对象 那就继续递归 否则就返回基本的数据类型
      }
      return newObject
    }
1
2
3
4
5
6
7

# 手写ajax

function get(){
  //创建ajax实例
  let req=new XMLHTTPRequest();
  if(req){
    //执行open 确定要访问的链接 以及同步异步
    req.open("GET", "http://test.com/?keywords=手机", true);
    //监听请求状态
    req.onreadystatechange=function(){
      if(req.readystate===4){
        if(req.statue===200){
          console.log('success')
        }else{
          console.log('error')
        }
      }
    }
    //发送请求
    req.send()
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Last Updated: 12/30/2022, 2:33:12 PM