前端常见手写代码

基础篇

1、防抖函数
/**
 * @description 防抖基础版本
 * @param {*} fn 
 * @param {*} delay 
 * @returns 
 */
function debuonce(fn, delay = 300) {
  let timer = null
  return function() {
    const that = this, args = arguments
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(that, args)
    }, delay)
  }
}

/**
 * @description 防抖支持立即执行版本
 * @param {*} fn 
 * @param {*} delay 
 * @param {*} immediate 
 * @returns 
 */
function immediateDebuonce(fn, delay = 300, immediate = true) {
  let timer = null
  let first = true
  return function() {
    const that = this, args = arguments
    if (immediate) {
      if (first) {
        fn.apply(that, args)
        first = false
      } else {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          fn.apply(that, args)
          first = true
        }, delay)
      }
    } else {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        fn.apply(that, args)
      }, delay)
    }
  }
}
2、节流函数
/**
 * @description 节流函数基础版本
 * @param {*} fn 
 * @param {*} delay 
 * @returns 
 */
function throttle(fn, delay = 300) {
  let timer = null
  return function() {
    const that = this, args = arguments
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(that, args)
      timer = null
    }, delay)
  }
}
3、new 关键字
function fnNew(ins, ...args) {
  // 创建一个对象
  let obj = {}
  // 让这个对象的 __proto__ 指向构造函数的原型
  obj = Object.create(ins.prototype)
  // 让构造函数的 this 指向这个对象
  const res = ins.apply(obj, args)
  // 如果构造函数的返回值是基本数据类型,就返回这个新对象,如果是引用类型就返回这个引用类型值
  return typeof res === 'object' ? res : obj
}
使用
function Ade(name) {
  let obj = {}
  obj.name = name
  return obj
}
function Ads(name) {
  this.name = name
}
console.log(fnNew(Ade, 'Ade'))
console.log(fnNew(Ads, 'Ads'))
4、instanceof 类型判断
function fnInstanceof(lt, rt) {
  if ((typeof lt !== 'object' || typeof lt !== 'function') || lt === null) {
    return false
  } 
  let proto = Object.getProtoTypeOf(lt)
  while(proto) {
    if (proto === rt.prototype) return true
      proto = Object.getPrototypeOf(proto)
    }
    return false
  } 
}
5、call、apply、bind
Function.prototype.fnCall(context = window, ...args) {
  if (typeof context !== 'object') context = new Object(context)
  const key = Symbol('call')
  context[key] = this
  const reslut = context[key](...args)
  delete context[key]
  return reslut
}
Function.prototype.fnApply(context = window, args) {
  if (typeof context !== 'object') context = new Object(context)
  const key = Symbol('apply')
  context[key] = this
  const reslut = context[key](...args)
  delete context[key]
  return reslut
}
Function.prototype.fnBind(context = window, ...args) {
  const that = this
  return function(...nextArgs) {
    const _args = [...args, ...nextArgs]
    return that.call(context, ..._args)
  }
}
6、深拷贝
/* 深拷贝基础版本,但是无法解决循环引用的问题 */
function fnDeepclone(target) {
  if (typeof target === 'object' && target !== null) {
    const cloneTarget = Array.isArray(target) ? []: {};
    for (let prop in target) {
      if (target.hasOwnProperty(prop)) {
        cloneTarget[prop] = fnDeepclone(target[prop]);
      }
    }
    return cloneTarget;
  } else {
    return target;
  }
}
创建循环引用对象
let obj = { a: 1 }
obj.traget = obj
此时使用 fnDeepclone 会报无限循环错误
/* 解决循环引用版本,使用 WeakMap 而不是使用 Map
   是因为 WeakMap 是弱类型即便被引用,也会被垃圾回收机制正常回收
*/
function _deepclone(traget, map = new WeakMap()) {
  const isObject = (typeof traget === 'object' || typeof traget === 'function') && traget !== null
  if (map.get(traget)) return traget
  if (isObject) {
    map.set(traget, true)
    let clone = Array.isArray(traget) ? [] : {}
    for (let key in traget) {
      if (traget.hasOwnProperty(key)) {
        clone[key] = _deepclone(traget[key], map)
      }
    }
    return clone
  } else {
    return traget
  }
}
7、使用 for of 遍历对象
class Symbol_iterator {
  constructor(traget) {
    if (!this.isObject(traget)) throw new Error('TypeError: traget type is not allowed')
    this.traget = traget
  }
  *[Symbol.iterator]() {
     const keys = Object.keys(this.traget)
     for (let i = 0; i < keys.length; i++) {
       yield { key: keys[i], value: this.traget[keys[i]] }
     }
    }
    isObject(traget) {
      const allowType = ['[object Array]', '[object Object]']
      return allowType.includes(Object.prototype.toString.call(traget))
    }
  }
}
使用
const user = { name: 'tom', age: 28 }
console.log(new Symbol_iterator(user))
// { key: name, value: 'tom' }
// { key: age, value: 28 }

const arr = [1, 2]
console.log(new Symbol_iterator(arr))
// { key: '0', value: 1 }
// { key: '1', value: 2 }
8、实现 a == 1 && a == 2 && a == 3 为真或 a === 1 && a === 2 && a === 3 为真
/* a == 1 && a == 2 && a == 3 */
let a  = { i: 0 }
a[Symbol.toPrimitive] = function() {
  return ++this.i
}

/* a === 1 && a === 2 && a === 3 */
let i = 0
Object.defineProperty(window, 'a', {
  get () {
    // 获取window.a的时候触发getter函数
    return ++i;
  }
})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值