JS手写源码(更新ing)

159 阅读1分钟

1.如何实现一个 new

function _new(fn, ...arg) {
  // 创建一个空的对象
  let obj = Object.create()
  // 链接到原型
  obj.__proto__ = fn.prototype
  // 绑定 this,执行构造函数
  let res = fn.apply(obj, arg)
  // 确保 new 出来的是个对象
  return res instanceof Object ? res : obj
}

2.如何实现一个 call

  function myCall(obj) {
  //把上下文this指向obj
    obj.__proto__._xx = this;
    var res = obj._xx(...Array.from(arguments));
    delete obj.__proto__._xx;
    return res;
  }

3.如何实现一个 apply

function myApply(obj, params) {
 //把上下文this指向obj
    obj.__proto__._xx = this;
    var res =obj._xx(...params);
    delete obj.__proto__._xx;
    return res
  }

4.如何实现一个 bind

  function myBind(obj) {
    var firstParams = [];
    for (var i = 1; i < arguments.length; i++) {
      firstParams.push(arguments[i]);
    }
    var _self = this;
    return function () {
      var lastParams = [];
      for (var i = 0; i < arguments.length; i++) {
        lastParams.push(arguments[i]);
      }
      obj.__proto__._xx = _self;
      obj._xx(...firstParams, ...lastParams);
      delete obj.__proto__._xx;
    }
  }

5.如何实现一个深拷贝

function deepClone(obj) {
  //判断对象类型
  let type = Object.prototype.toString.call(obj).slice(8, -1)
  let _new = null
  if (type === 'Array') {
    _new = []
    obj.forEach((item) => {
      _new.push(item)
    })
  } else if (type === 'Object') {
    _new = {}
    //遍历递归
    for (let key in obj) {
      _new[key] = deepClone(obj[key])
    }
  } else {
    return obj
  }
  return _new
}

6.如何实现一个函数防抖

function debounce(fn, wait){
  let timer = null
  return function(){
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, wait)
  }
}

7.如何实现一个函数节流