Loading

「跟着渡一学前端」手写call函数

完整代码

Function.prototype.myCall = function (ctx, ...args) {
  ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
  const fn = this;
  const key = Symbol();
  Object.defineProperty(ctx, key, {
    value: fn,
    enumerable: false,
  });
  const r = ctx[key](...args);
  delete ctx[key];
  return r;
}

function method(a,b){
  console.log('args',a,b);
  console.log('this',this);
}

method.myCall(1,2,3);

具体分析

  1. 写在哪?——写到函数原型(Function.prototype)上

  2. 有哪些参数?

  3. 对第一个参数(即对需要绑定的this参数)进行处理

  4. 绑定this

posted @ 2025-02-15 09:07  lao-jiawei  阅读(8)  评论(0)    收藏  举报