apply、bind、call区别和手写代码

apply、bind、call区别和手写代码

1.相同

改变函数运行时的this指向,即执行上下文(第一个参数,若参数未设置或为null\undefined,则指向全局window对象);

2.区别

  • 三者都可以传参,apply是数组,而callbind是参数列表,且applycall是一次性传入参数,而bind可以分为多次传入
  • applycall 则是立即执行, bind 是返回绑定this之后的函数
  • apply只是临时改变this指向一次,bind返回的是永久改变this指向的函数
fn.apply(null,[1,2,3]); // this指向window
fn.call(obj,1,2,3); // this会变成传入的obj;
const bindFn = fn.bind(obj,1); // this 也会变成传入的obj ,bind不是立即执行需要执行一次
bindFn(2,3) // this指向obj

3.手写

1.apply(传入数组)

// obj 绑定的对象 arrs数组参数
Function.prototypr.myApply= function (obj,arrs){
    // 1处理为nunll undefined
    obj = obj || window;
    // 2. 将当前函数 (this) 挂载到 obj 上
    obj._fn = this;
    // 3.执行函数
    let result = obj._fn(...args);
    // 4.清理挂载的函数
    delete obj.__fn;
    return result;
}

2.call(与apply类似,传入列表)

Function.prototype.myCall(obj,...args){
    obj = obj || window;
    obj._fn = this;
    const result = obj._fn(...args);
    delete obj._fn;
    return result;
}

3.bind(和call类似,但多次传入参数,返回函数)

Function.prototype.myBind(obj,...args1){
    obj = obj || window;
    let _this = this;
    return function (...args2){
        // 合并传入的参数
   		 const allArgs = [...args, ...newArgs];
        // 这里和call类似
        obj._fn = _this;
        const result = obj._fn(...allArgs);
        delete obj._fn;
        return result;
        // 或者直接使用call
        // return _this.call(obj,allArgs);
    }
}
posted @ 2026-01-19 11:55  DurianTRY  阅读(3)  评论(0)    收藏  举报