前端手写: call, allpy, bind

4 阅读1分钟
// 1. 手写call 
Function.prototype.myCall = function (con, ...args) {
  con = con || window;
  con.fn = this;
  const res = con.fn(...args);
  delete con.fn
  return res;
}

let obj1 = { name: '李四' };
function test(a, b) {
  console.log(this.name, a, b);
}
test.myCall(obj1, 10, 20); // 李四 10 20

// 2. 手写apply 特点:第二个参数是数组 / 类数组
Function.prototype.myApply = function (con, arr) {
  con = con || window;
  con.fn = this;
  const args = arr || [];
  const res = con.fn(...args)
  delete con.fn;
  return res;
}
test.myApply(obj1, [100, 200])


// 3. 手写bind 绑定 this + 柯里化传参

Function.prototype.myBind = function (content, ...args1) {
  const fn = this;
  return function (...args2) {
    fn.apply(fn, [...args1, ...args2])
  }
}
function fn(a, b, c) {
  console.log(this.name, a, b, c)
}
let obj = {
  name: '张三'
}

let newFn = fn.myBind(obj, 10, 20);

newFn(30);