手写call、apply、bind,强化自身记忆

187 阅读1分钟

话不多说,直接上手写就对了

call

主要是理解函数调用的时候谁调用this指向谁

Function.prototype.myCall = function(ctx){
  ctx = ctx || window
  ctx.fn = this
  let args = [...arguments].slice(1)
  let result = ctx.fn(...args)
  delete.ctx.fn
  return result
}

apply

与call的差异在于传参不一样

Function.prototype.myApply = function(ctx, agrs){
  ctx = ctx || window
  ctx.fn = this
  let result = ctx.fn(...args)
  delete ctx.fn
  return result
}

bind

需要考虑返回的函数被当做构造函数实例化的时候,要指向函数本身

Function.prototype.myBind = function(ctx){
  let fn = this
  let args = [...arguments].slice(1)
  let _tempFn = function(){}
  let newFn = function(){
      let newArgs = [...arguments]
      return fn.apply(this instanceof newFn ? fn : ctx, args.concat(newArgs))
  }
  _tempFn.prototype = this.prototype
  newFn.prototype = new _tempFn()
  return newFn
}

调用例子

var obj = {
      job: 'IT',
      age: 18
    }
function print(sex, wage) {
  console.log('--', this.job, this.age, sex, wage);
}
print.myCall(obj, '测试', 30001)
print.myApply(obj, ['测试', 30000])
let myPrint = print.myBind(obj, '测试')
let b2 = new myPrint(99)

小结

对于经常使用到的一些js方法,需要我们不断的去自己实现,从而才能够真正的掌握