手写函数常用方法bind、call、apply

/**
 *  记录当前函数,返回一个新函数
 *  1、通过new 调用新函数:如果原始函数返回的是一个对象,则返回该对象,否则返回构造函数为原始函数的新对象
 *  2、将剩余参数和执行新函数的参数合并,使用指定的this去执行新函数,返回值由原始函数决定
 * @param {*} ctx
 * @param  {...any} args
 * @returns
 */
Function.prototype.myBind = function (ctx, ...args) {
  const Fn = this;
  return function (...rest) {
    if (new.target) {
      return new Fn(...args, ...rest);
    } else {
      return Fn.apply(ctx, [...args, ...rest]);
    }
  };
};

/**
 * call改变this指向为第一个参数对象,然后该对象使用剩余参数执行函数,并返回结果
 * @param {this指向} ctx
 * @param  {...any} args
 * @returns
 */
Function.prototype.myCall = function (ctx, ...args) {
  //globalThis 浏览器环境指向window,node环境指向global
  ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
  const key = Symbol();
  Object.defineProperty(ctx, key, {
    value: this,
    enumerable: false,
  });
  const result = ctx[key](...args);
  delete ctx[key];
  return result;
};

/**
 *  apply方法和call方法类似,不过apply方法只传两个参数,第二个参数会以数组形式传递
 * @param {} ctx
 * @param {*} argsArr
 * @returns
 */
Function.prototype.myApply = function (ctx, argsArr) {
  if (!argsArr) {
    argsArr = [];
  }
  if (argsArr && typeof argsArr === "object") {
    argsArr = Array.from(argsArr);
  } else {
    throw TypeError("CreateListFromArrayLike called on non-object");
  }
  ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
  const fn = this;
  const key = Symbol();
  Object.defineProperty(ctx, key, {
    value: fn,
    enumerable: false,
  });
  const result = ctx[key]();
  delete ctx[key];
  return result;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值