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

  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://juejin.cn/post/7248995705292292153 作者:总瓢把子

(0)
上一篇 2023年6月27日 上午10:17
下一篇 2023年6月27日 上午10:27

相关推荐

发表回复

登录后才能评论