前端常见手写功能

150 阅读1分钟
手写instanceof
function customInstance(L, R) {
 var RP = R.prototype 
 var LP = L.__proto__ 
 while (true) { 
   if(LP == null) { 
     return false 
   } 
   if(LP == RP) { 
     return true 
   } 
   LP = LP.__proto__ 
  } 
 } 
 console.log(customInstance({},Object));
手写call
Function.prototype.myCall = function (context) {
    if (typeof this !== 'function') {
      throw new TypeError("Not a Function")
    }
    context = context || window
    context.fn = this
    let args = Array.from(arguments).slice(1)   
    let result = context.fn(...args)
    delete context.fn
    return result
  }
手写bind
Function.prototype.myBind = function(context){
    if(typeof this !== "function") {
      throw new TypeError("Not a Function")
    }
    const _this = this 
    const args = Array.prototype.slice.call(arguments,1)
    return function F () {
      if(this instanceof F) {
        return new _this(...args,...arguments)
      }else{
        return _this.apply(context,args.concat(...arguments))
      }
    } 
  }
手写apply
Function.prototype.myApply = function (context) {
    if (typeof this !== "function") {
      throw new TypeError("Not a Function")
    }
    let result
    context = context || window
    context.fn = this
    if (arguments[1]) {
      result = context.fn(...arguments[1])
    } else {
      result = context.fn()
    }
    delete context.fn
    return result
  }

手写 new
function myNew(fn, ...args) {
   obj.__proto__ = fn.prototype 
   let result = fn.apply(obj, args) 
   return result instanceof Object ? result : obj 
}