JavaScript中如何手写一个bind方法

在js中可以使用bind方法来改变函数内部this的指向,那我们如何自己手写一个bind方法呢?这也是一个常见的面试题。
在我们手写bind方法之前,有几个需要注意的地方:

  1. bind方法第一个参数接收的是this要指向的对象
  2. bind方法是通过参数列表的形式传参的
  3. bind方法不会立即执行原函数,而是返回一个新的函数

代码如下:

/**
 * 手写bind方法
 */
// bind方法第一个参数接收的是this要指向的对象,后面是传递的是参数
Function.prototype.myBind = function(ctx, ...args) {
    
    
    // 如果ctx为undefined || null的话,默认是window对象
    ctx = ctx == null ? window : ctx
    // 取得要被调用的原函数
    const self = this
    // 获取到原函数参数的长度
    const len = self.length
    // bind方法不会立即调用函数,而是返回一个新函数
    return function(...arrs) {
    
    
        // 根据原函数参数的长度,得到需要传给原函数的参数
        const params = [...args, ...arrs].slice(0, len)
        return self.apply(ctx, params)
    }

}

function fn(x, y) {
    
    
    console.log('this:', this)
    return x + y
}

const newFn = fn.myBind({
    
    id: 1})

console.log(newFn(4, 5))

以上代码简单实现的一个bind方法,如果有大佬发现以上代码有存在不足的地方还望指出改正!

猜你喜欢

转载自blog.csdn.net/m0_37873510/article/details/126414614