第一篇 手写原理代码 - 函数【 apply、call、bind 】

apply, call 和 bind 都是 JavaScript 中用于控制函数调用时 this 关键字指向的工具。它们可以将需要执行的函数和需要绑定的作用域传入,以便在调用时确保正确的上下文

apply 和 call 传递的参数列表有所不同。apply 接受的参数是一个数组,而 call 接受的是一组参数列表。如果你的参数是数组,则使用 apply 更加合适;否则,使用 call 会更方便

bind 方法不会立即执行函数,而是返回一个函数,并将其与指定的上下文和参数一起绑定。这意味着你可以在之后的任何时候调用它,或者将它传递给其他函数

总的来说,这三个方法都是用来改变 this 指向的。如果你需要立即调用函数并传递参数,则可以使用 apply 或 call 方法。如果你想要创建一个新函数并将上下文和参数一起绑定,则可以使用 bind 方法。

1、apply

Function.prototype.myApply = function (context, arg = []) {
  context = context ?? window;
  const key = Symbol();

  context[key] = this;

  const result = context[key](...arg);

  delete context[key];

  return result;
};
2、call
Function.prototype.myCall = function (context, ...arg) {
  context = context ?? window;

  const key = Symbol();

  context[key] = this;

  const result = context[key](...arg);

  delete context[key];

  return result;
};

3、bind

Function.prototype.myBind = function (context, ...arg) {
  context = context ?? window;

  const key = Symbol();

  context[key] = this;

  const result = context[key](...arg);

  delete context[key];

  return function () {
    return result;
  };
};

使用

var name = "caix";

let obj = {
  name: "caix from obj",
};

function getName(age, sex) {
  return `${this.name} 今年 ${age} 岁, 他是 ${sex} 的`;
}

const getBind = getName.myBind(obj, "36", "男");

console.log("myApply", getName.myApply(obj, ["36", "男"]));

console.log("myCall", getName.myCall(null, "36", "男"));

console.log("myBind", getBind());
posted @ 2023-04-11 23:07  caix-1987  阅读(45)  评论(0)    收藏  举报