手写 apply call bind 三个方法

call,apply,bind。其实呢这三兄弟都是为了改变函数的上下文而存在的,或者可以简单点说就是用来改变this指向的。但是呢这三兄弟的用法还是有区别的。

1、apply和call会让当前函数立即执行,而bind会返回一个函数,后续需要的时候再调用执行

2、apply最多只能有两个参数,而call,bind可以有多个参数,第一个参数和apply一样,是用来替换的对象,后边是参数列表

Function.prototype.Mycall = function (context) {
    const that = context || window ;
    that.ctx = this;
    const args = Array.from(arguments).slice(1);
    const result  = arguments.length > 1 ? that.ctx(...args) : that.ctx();
    delete that.ctx;
    return result; 
  }


 Function.prototype.MyApply = function(context){   // apply 传参第二个参数为数组!!!需要注意一点  
  const ctx = context || window;

ctx.func = this;const

const res = arguments[1] ? ctx.func(...arguments[1]):ctx.func();

delete ctx.func;

return res

}



Function.prototype.MyBind = function(context){ // 然后 bind 返回的是一个函数!!!
  const cxt = JSON.parse(JSON.stringify(context)) || window;
  cxt.func = this;
  const args = Array.from(arguments).slice(1);
  console.log(arguments,'a')
  return function(){
    const allArgs = args.concat(Array.from(arguments));
    console.log(allArgs, 'b');
    return allArgs.length > 0 ? cxt.func(...allArgs):cxt.func();
  }
}
 
原文地址:https://www.cnblogs.com/Hijacku/p/15011252.html