实现一个bind函数

Mr.Hotsuitor小于 1 分钟javascriptbind

实现 bind 函数可以分解为三步:

  • 修改 this 指向
  • 动态传递参数
// 方式一:只在bind中传递函数参数
fn.bind(obj,1,2)()

// 方式二:在bind中传递函数参数,也在返回函数中传递参数
fn.bind(obj,1)(2)
  • 兼容 new 关键字
/*
 * File Created: Thursday, 20th April 2023 6:02:11 pm
 * Author: hotsuitor (hotsuitor@qq.com)
 * -----
 * Last Modified: Thursday, 20th April 2023 6:06:31 pm
 * Modified By: hotsuitor (hotsuitor@qq.com>)
 */

Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError(`${this} is Not a Function`)
  }

  const args = [...arguments].slice(1),
    fn = this

  return function Fn() {
    // 根据调用方式,传入不同绑定值
    fn.apply(
      this instanceof Fn ? new fn(...arguments) : context,
      args.concat(...arguments)
    )
  }
}