手动实现call、apply、bind

42 阅读1分钟

先上代码

Function.prototype.myCall = function () {
  let context = arguments[0] || window;
  let args = [...arguments].slice(1);
  context.fn = this;
  context.fn(...args);
};

Function.prototype.myApply = function () {
	let context = arguments[0] || window;
  let args = [...arguments].slice(1);
  context.fn = this;
  context.fn(...args[0]);
};

Function.prototype.myBind = function () {
	let context = arguments[0] || window;
  let args = [...arguments].slice(1);
  context.fn = this;
  return function () {
    context.fn(...args[0]);
  };
};
var obj = { name: "darren" };
var name = "allen";
var getName = function (age, job) {
  console.log(age, job, "age, job");
  console.log(this.name);
};
getName.myCall(obj, 12, "h5");
getName.myApply(obj, [12, "h5"]);
getName.myBind(obj, [12, "h5"])();
// 返回相同 darren 12 h5

call、apply、bind

特点

  • 三者都可用来改变函数的this对象的指向的;
  • 三者的第一个参数都是this要指向的对象,也就是想指定的上下文;
  • 三者都可以利用后续参数传参;
  • 另外bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用