手写apply,call,bind

Function.prototype.myApply = function (context) {
  if (context === undefined || context === null) {
    context = globalThis;
  } else {
    context = Object(context);
  }

  let fn = Symbol("myFn");
  context[fn] = this;
  let result;
  let arg = arguments[1];
  if (!Array.isArray(arg)) {
    result = context[fn]();
  } else {
    let _arg = Array.from(arg);
    result = context[fn](..._arg);
  }
  delete context[fn];
  return result;
};

Function.prototype.myCall = function (context) {
  if (context === undefined || context === null) {
    context = globalThis;
  } else {
    context = Object(context);
  }

  let fn = Symbol("myFn");
  context[fn] = this;
  let result;

  if (arguments.length > 1) {
    let arg = Array.from(arguments).slice(1);
    context[fn](...arg);
  } else {
    context[fn]();
  }

  delete context[fn];
  return result;
};
//apply实现bind
Function.prototype.myBind = function (context, ...arg) {
  let fn = this;
  let args = arguments;
  return function (...callArgs) {
    return fn.apply(context, args.length > 1 ? arg.concat(callArgs) : null);
  };
};
//call实现bind
Function.prototype.myBind2 = function (context, ...arg) {
  let fn = this;
  let args = arguments;
  return function (...callArgs) {
    let _args = args.length > 1 ? [...arg, ...callArgs] : callArgs;
    return fn.call(context, ..._args);
  };
};
const person = {
  name: "Alice",
  greet: function () {
    console.log(`Hello, ${this.name}!`);
  },
};

const anotherPerson = {
  name: "Bob Apply",
};
const anotherCallPerson = {
  name: "Bob Call",
};
const anotherBindPerson = {
  name: "Bob Bind",
};

// 使用 apply 方法改变 greet 函数执行时的上下文为 anotherPerson
person.greet.myApply(anotherPerson); // 输出:Bob Apply
person.greet.myCall(anotherCallPerson); // 输出:Bob Call
person.greet.myBind(anotherBindPerson)(); // 输出:Bob Bind

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值