apply、call、bind区别和模拟实现apply、call、bind

231 阅读1分钟

区别



let a = {
    name: 'zz',
    age: 11,
    say(a, b){
        console.log(this.name, this.age, a, b)
    }
}

let b = {
    name: 'zzz',
    age: 12
}

let c = a.say.bind(b, 111, 222)

a.say() // zz 11 undefined undefined

a.say.call(b, 1, 2) // zzz 12 1 2

a.say.apply(b, [11,22]) // zzz 12 11 22

c() // zzz 12 111 222

模拟实现

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)
    }
  }