Skip to content

call apply bind ​

2023-04-20 19:17:33

call ​

call方法可以在调用函数时将 this 的指向改变为指定的对象,同时将函数的参数作为一个一个的参数进行传递。它的语法如下:

ts
func.call(thisArg, arg1, arg2, ...)

实现

ts
Function.prototype.myCall = function (context, ...args) {
  const fn = Symbol('fn') // 声明一个独有的 Symbol 属性,防止 fn 被占用

  // 如果没有传入上下文,那么默认为 window
  context = context || window

  // 将调用函数设为对象的方法
  context[fn] = this

  // 调用函数并返回结果
  const result = context[fn](...args)

  // 删除调用函数的属性
  delete context[fn]

  return result
}

apply ​

apply与call类似,但是传参必须是一个数组

实现

ts
Function.prototype.myApply = function (context, args) {
  const fn = Symbol('fn')

  context = context || window

  context[fn] = this

  const result = context[fn](...args)

  delete context[fn]

  return result
}

bind ​

bind改变this指向后不会立即执行,而是返回一个永久改变this指向的函数

实现

ts
Function.prototype.myBind = function (context, ...args) {
  const fn = this

  // 返回一个新的函数
  return function (...newArgs) {
    // 使用 apply 方法将 fn 函数体内的 this 指向 context
    return fn.apply(context, [...args, ...newArgs])
  }
}

Released under the MIT License.