Analog implementation apply, call, bind

1、call

 Function.prototype.myCall = function (context) {
    var c = context || window
    var args = Array.from(arguments).slice(1)
    
    c.___fn = this

    var result = c.___fn(...args)
    delete c.___fn
    return result
  }
复制代码

2、apply

 Function.prototype.myApply = function (context) {
    var c = context || window

    c.__fn = this
    
    var args = Array.from(arguments)[1]
    var result = args ? c.__fn(...args) : c.__fn()

    delete c.__fn
    return result
  }
复制代码

3、bind

  Function.prototype.myBind = function (context) {
    var _this = this
    var oldArgs = Array.from(arguments).slice(1)


    return function () {
      var finArgs = oldArgs.length ? oldArgs : Array.from(arguments)
      return _this.apply(context, finArgs)
    }
  }
复制代码

Reproduced in: https: //juejin.im/post/5d099f6ff265da1ba431f113

Guess you like

Origin blog.csdn.net/weixin_33834910/article/details/93165226