Code前端首页关于Code前端联系我们

前端面试题 – 99. 手写call apply bind

terry 2年前 (2023-09-10) 阅读数 78 #前端教程
  1. 实现call函数:
  • 明确下Context
  • 将当前函数作为Context的一个内置方法
  • 然后用上下文的内置方法执行,就把函数的this替换为Context了。
Function.prototype.myCall = function (context, ...args) {
  context = context || window;
  const fn = Symbol('fn');
  context[fn] = this;// 将myCall方法绑定
  const result = context[fn](...args);
  delete context[fn];
  return result;
};

使用

function greet(name) {
  console.log(`Hello, ${name}! I'm ${this.name}.`);
}

const person = {
  name: 'Alice'
};

greet.myCall(person, 'Bob');
// 输出:Hello, Bob! I'm Alice.

  1. 实现apply函数:
Function.prototype.myApply = function (context, args) {
  context = context || window;
  const fn = Symbol('fn');
  context[fn] = this;
  const result = context[fn](...args);
  delete context[fn];
  return result;
};

使用

function greet(name, age) {
  console.log(`Hello, ${name}! I'm ${this.name} and I'm ${age} years old.`);
}

const person = {
  name: 'Alice'
};

greet.myApply(person, ['Bob', 25]);
// 输出:Hello, Bob! I'm Alice and I'm 25 years old.

  1. 实现bind函数:
  • 返回一个新的函数,通过self.apply(context替换掉上下文
  • 绑定后是个新的函数,可能有新的参数
Function.prototype.myBind = function (context, ...args) {
  const self = this;
  return function (...innerArgs) {
    return self.apply(context, args.concat(innerArgs));
  };
};

使用

function greet(name) {
  console.log(`Hello, ${name}! I'm ${this.name}.`);
}

const person = {
  name: 'Alice'
};

const boundGreet = greet.myBind(person);
boundGreet('Bob');
// 输出:Hello, Bob! I'm Alice.

原文链接:https://www.codeqd.com/zb_users/upload/2023/09/7248995705292292153 作者:总瓢把子

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门