javascript中call apply bind的实现

145 阅读1分钟

文章目录


call

封装一个很简单的函数,简单的理解一下call的工作机制。不考虑各种传参问题,假设按正常规则进行传参。

Function.prototype.fnCall = function (thisArg, ...args) {
  const fn = this;  // this指向sum函数
  // 要转为一个对象类型,Object()的作用在讲对象时已经说过
  thisArg = thisArg !== undefined && thisArg !== null ? Object(thisArg) : window;
  thisArg.fn = fn;  // 当作属性挂在显示绑定的值上
  const res = thisArg.fn(...args);
  delete thisArg.fn; // 删除手动添加的属性
  return res;
};

function sum(a, b) {
  return a + b;
}
const res = sum.fnCall("a", 10, 20);
console.log(res);  // 30

apply

Function.prototype.fnApply = function (thisArg, args) {
  const fn = this;
  thisArg = thisArg !== undefined && thisArg !== null ? Object(thisArg) : window;
  thisArg.fn = fn;
  args = args || [];
  const res = thisArg.fn(...args);
  delete thisArg.fn;
  return res;
};

function sum(a, b) {
  return a + b;
}
const res = sum.fnApply("a", [10, 20]);
console.log(res);  // 30

bind

Function.prototype.fnBind = function (thisArg, ...args) {
  const fn = this;
  thisArg = thisArg !== undefined && thisArg !== null ? Object(thisArg) : window;
  thisArg.fn = fn;
  return function (...argsbind) {
    const res = thisArg.fn(...[...args, ...argsbind]);
    delete thisArg.fn;
    return res;
  };
};

function sum(a, b) {
  return a + b;
}
const res1 = sum.fnBind("a", 10, 20)();
const res2 = sum.fnBind("a", 10)(20);
console.log(res1);  // 30
console.log(res2); // 30