手写函数 bind、call、apply

bind 应用

- 返回一个新的函数(旧函数不会更改),但不执行

- 绑定 `this` 和部分参数

- 如果是箭头函数,无法改变 `this` ,只能改变参数

function fn(a, b, c) {
    console.log(this, a, b, c)
}
const fn1 = fn.bind({x: 100})
fn1(10, 20, 30) // {x: 100} 10 20 30
const fn2 = fn.bind({x: 100}, 1, 2)
fn2(10, 20, 30) // {x: 100} 1 2 10 (注意第三个参数变成了 10)

fn(10, 20, 30) // window 10 20 30 (旧函数不变)

思路

- 返回新函数

- 重新绑定 `this`

- 同时绑定执行的参数(apply 或者 call)

/**
 * @description 手写 bind
 */

// @ts-ignore
Function.prototype.customBind = function (context: any, ...bindArgs: any[]) {
    // context 是 bind 传入的 this
    // bindArgs 是 bind 传入的各个参数

    const self = this // 当前的函数本身

    return function (...args: any[]) {
        // 拼接参数
        const newArgs = bindArgs.concat(args)
        return self.apply(context, newArgs)
    }

猜你喜欢

转载自blog.csdn.net/m0_38066007/article/details/124962843