JS手写call、bind、apply

call方法的实现

  Function.prototype.MyCall = function(content,...args){

    const self = content || window;

    const args = args.slice(1)

    const self.fn = this

    const result = self.fn(args)

    delete self.fn

    return result

  }

apply方法实现,和call方法差不多

  Function.prototype.MyApply = function(content,args = []){

    const self = content || window

    self.fn = this;

    let result = null

    if(args.length > 0){

      const  = self.fn(args)

    }else {

      result = self.fn()

    }

    delete self.fn

    return result

  }

稍显麻烦的bind方法

 Function.prototype.MyBind = function(content){

   const self = this

   const args = arguments.slice(1)

   return function F(){

     if(this instanceof F){   //通过new的方式

       return new self(...args,...arguments)

     }else{

       const doubleArgs = args.concat(arguments)

       return self.apply(content,doubleArgs)

        }

   }

 }

posted @ 2020-03-31 16:38  小白白又白啦  阅读(582)  评论(0编辑  收藏  举报