手写实现call、apply和bind函数

手写 call 函数

/**
 * 手写 call 函数
 * @param {*} context
 * @returns
 */
const myCall = function (context) {
   
  if (typeof this !== "function") return TypeError("not a function");
  const ctx = context || window;
  const args = [...arguments];
  args.splice(0, 1);
  ctx.fn = this;
  const ret = ctx.fn(...args);
  delete ctx.fn;
  return ret;
};

// test
const a = 789;
const obj = {
    a: 123, b: 456 };
const fn = function () {
   
  console.log(this.a);
};
fn.myCall = myCall;

fn.myCall(obj); // 123

手写 apply 函数

/**
 * 手写 apply 函数
 * @param {*} context
 * @returns
 */
const myApply = function (context) {
   
  if (typeof this !== "function") return TypeError("not a function");
  const ctx = context || window;
  const args = [...arguments]?.[1];
  ctx.fn = this;
  let ret = null;
  if (Array.isArray(args) && args.length > 0) {
   
    ret = ctx.fn(...args);
  } else {
   
    ret = ctx.fn();
  }
  delete ctx.fn;
  return ret;
};

// test
const a = 789;
const obj = {
    a: 123, b: 456 };
const fn = function () {
   
  console.log(this.a);
};
fn.myApply = myApply;

fn.myApply(obj); // 123

手写 bind 函数

/**
 * 手写 bind 函数
 * @param {*} context
 * @param  {...any} args1
 * @returns
 */
const myBind = function (context, ...args1) {
   
  if (typeof this !== "function") return TypeError("not a function");
  const ctx = context || window;
  ctx.fn = this;
  return function (...args2) {
   
    const args = [...args1, ...args2];
    const ret = ctx.fn(...args);
    delete ctx.fn;
    return ret;
  };
};

// 测试
function sum(num1, num2) {
   
  console.log(num1, num2, this);
}

sum.myBind = myBind;

// 原生的 bind() 方法
const Fn = sum.bind({
    name: "bind" }, 1);
Fn(2);

// 自定义的 myBind() 方法
const Fn1 = sum.myBind({
    name: "myBind" }, 1);
Fn1(2);

相关推荐

  1. 实现call、applybind函数

    2024-02-02 20:10:04       50 阅读
  2. 实现instanceof

    2024-02-02 20:10:04       22 阅读
  3. 7.call函数

    2024-02-02 20:10:04       54 阅读
  4. 实现防抖

    2024-02-02 20:10:04       31 阅读
  5. uniapp 签名实现

    2024-02-02 20:10:04       26 阅读
  6. 实现getUrlParams方法

    2024-02-02 20:10:04       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-02 20:10:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-02 20:10:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-02 20:10:04       82 阅读
  4. Python语言-面向对象

    2024-02-02 20:10:04       91 阅读

热门阅读

  1. Unity之延迟函数

    2024-02-02 20:10:04       63 阅读
  2. SpringBoot+JdbcTempalte+SQLServer

    2024-02-02 20:10:04       53 阅读
  3. centos7 时区设置 时间同步

    2024-02-02 20:10:04       45 阅读
  4. 基于python的新闻爬虫

    2024-02-02 20:10:04       59 阅读