1.call

  1. Function.prototype.myCall = function(context = window,...args) {
  2. let fn = this,
  3. res = null;
  4. context.$fn = fn;
  5. res = context.$fn(...args);
  6. delete context.$fn;
  7. return res;
  8. }

注意:一个call是让左边函数执行(this是传递的参数),多个call是让最后传参的函数执行(this是window/undefined)

  1. function fn1(){ console.log(1) }
  2. function fn2(){ console.log(2) }
  3. fn1.call(fn2)
  4. fn1.call.call(fn2)
  5. Function.prototype.call(fn1)
  6. Function.prototype.call.call(fn1)
  7. //输出结果:
  8. //1 2 无输出 1

2.apply

  1. Function.prototype.myApply = function(context = window,args) {
  2. let fn = this,
  3. res = null;
  4. context.$fn = fn;
  5. res = context.$fn(...args);
  6. delete context.$fn;
  7. return res;
  8. }

3.bind

  1. Function.prototype.myBind = function(context = window,...outerArg) {
  2. let fn = this,
  3. fnNOP = function(){};
  4. context.$fn = fn;
  5. let fnBound = function(...innerArgs) {
  6. res = fn.apply(this instanceof fn ? this : context,outerArgs.concat(innerArgs))
  7. }
  8. fnNOP.prototype = fn.prototype;
  9. fnBound.prototype = new fnNOP();
  10. return fnBound;
  11. }