重学JavaScript

手写 call 、apply、bind

2021-02-03  本文已影响0人  阿畅_

基本介绍

apply、call、bind
都是Function 对象上的方法,调用这三个方法必须是一个函数。

fn.call(thisArg, param1, ... paramN)
fn.apply(thisArg, [param1, ... paramN])
fn.bind(thisArg, param1, ... paramN)

fn 是要调用的函数
thisArg 是 this 所指向的对象
param 是参数

  let A = {
    name: 'A',
    getName: function (msg) {
      return msg + this.name
    }
  }

  let B = {
    name: 'B'
  }
  console.log('call ->', A.getName.call(B, 'Hello ')) // call -> Hello B
  console.log('apply ->', A.getName.apply(B, ['Hello '])) // apply -> Hello B
  const getName = A.getName.bind(B, 'Hello ')
  console.log('bind ->', getName()) // bind -> Hello B

手写 call

Function.prototype.myCall = function(context, ...args) {
  const ctx = context || window
  ctx.fn = this
  const result = eval('ctx.fn(...args)')
  delete ctx.fn
  return result
}

// 测试
 console.log('myCall --->', A.getName.myCall(B, 'Hello ')) // myCall ---> Hello B

手写 apply

Function.prototype.myApply = function (context, args) {
  const ctx = context || window
  ctx.fn = this
  const res = eval('context.fn(...args)')
  delete ctx.fn
  return res
}
// 测试
console.log('myApply --->', A.getName.myApply(B, ['apply ']))
// myApply ---> apply B

手写 bind

 Function.prototype.myBind = function (context, ...args) {
  if (typeof this !== 'function') throw new Error('this must be a function')
  let self = this
  let res = function () {
    // 这里如果执行可能还会有参数,需要和之前的参数合并 Array.prototype.slice.call(arguments)
    return self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)))
  }
  // 如果原型上有方法
  if (this.prototype) {
    res.prototype = Object.create(this.prototype)
  }
  return res
}

// 测试
const mbind = A.getName.myBind(B, 'my bind ')
console.log('my bind-->', mbind()) // my bind--> my bind B
上一篇下一篇

猜你喜欢

热点阅读