js手写 call 、apply、 bind

call
    function Fn(a, b, c) {
      console.log(this.msg, a, b, c)
    }
    const o = {
      msg: 'hello, world!',
      fn1: function () {
        console.log(this.msg)
      }
    }
    // Fn.call(o)
    // Function.prototype.myCall = function(o, ...args) {
    //   o.fn = this
    //   o.fn(...args)
    //   delete o.fn
    //   o.fn1()
    // }
    Function.prototype.myCall = function(o) {
      const newArgs = []
      for(let i = 1; i < arguments.length; i++) {
        newArgs.push("arguments["+i+"]")
      }
      o.fn = this
      const res = eval("o.fn("+ newArgs +")")
      delete o.fn
      return res
    }
    Fn.myCall(o, ['aa'], 2, 3) // hello, world!  ['aa'] 2 3
apply
    Function.prototype.myApply = function(o, arrArgs) {
      const newArgs = []
      o.fn = this
      let res = null
      if (!arrArgs) {
        res = o.fn()
      } else {
        for(let i = 0; i < arrArgs.length; i++) {
          newArgs.push("arrArgs["+i+"]")
        }
        res = eval("o.fn("+ newArgs +")")
      }
      delete o.fn
      return res
    }
    Fn.myApply(o, [['aa'], 2, {a: '11'}]) // hello, world!  ['aa'] 2 {a: '11'}
bind
Function.prototype.myBind = function(o) {
      const that = this
      const args1 = Array.prototype.slice.call(arguments, 1)
      let args2 = null
      return function() {
        // 这里是Window // console.log(this)
        args2 = Array.prototype.slice.call(arguments)
        that.apply(o, args1.concat(args2))
      }
    }
    Fn.myBind(o, 'aa')('a', 'b', 'c') // hello, world! aa a b
posted @ 2021-12-08 14:14  春风一笑  阅读(57)  评论(0)    收藏  举报