JS手写——call bind apply

手写call

js 复制代码
// 手写call,将调用myCall的函数传递给context
Function.prototype.myCall = function(context,...args) {
  context = context ?? globalThis;
  const a = Symbol();
  context[a] = this;
  const result = context[a](...args);
  delete context[a];
  return result;
}

const obj = {name : 'Tom'};
function greet(age,city) {
  console.log(`${this.name},${age},${city}`);
}
greet.myCall(obj,18,'USa');

手写apply

js 复制代码
// 逻辑和call一样,就是接受的是参数数组
Function.prototype.myApply = function(context,argArray) {
  context = context ?? globalThis;
  const a =Symbol();
  context[a] = this;
  let result;
  if(Array.isArray(argArray)) {
    result = context[a](...argArray);
  }else {
    result = context[a]();
  }
  delete context[a];
  return result;
}

const obj = {name : 'Tom'};
function greet(age,city) {
  console.log(`${this.name},${age},${city}`);
}
greet.myApply(obj,[18,'usa']);

手写bind

js 复制代码
// 手写bind
Function.prototype.myBind = function(context,...args) {
  context = context ?? globalThis;
  const fn = this;
  const bound = function(...rest) {
    if(this instanceof bound) {
      return new fn(...args,...rest);
    }else {
      return fn.call(context,...args,...rest);
    }
  }
  // 保证:new bound() instanceof fn === true
  bound.prototype = Object.create(fn.prototype);
  return bound;
}




const person = {
 name: 'itheima'
}
function func(numA, numB, numC, numD) {
 console.log(this)
 console.log(numA, numB, numC, numD)
 return numA + numB + numC + numD
}

const bindFunc = func.myBind(person, 1, 2)

new bindFunc(3,4);
console.log(new bindFunc(5,6) instanceof func);
相关推荐
kyriewen12 小时前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
IT_陈寒12 小时前
Java的Date类又坑了我一次,改用时间戳真香
前端·人工智能·后端
山河木马13 小时前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
小林攻城狮13 小时前
使用 Transport 节流解决 Vercel AI SDK 流式渲染卡死问题
前端·react.js
前端缘梦13 小时前
告别 TS 运行时类型漏洞!Zod 完整入门实战教程(前端 / 全栈必备)
前端·react.js·全栈
the_answer13 小时前
Webpack vs Vite 深度对比分析
前端·webpack
转转技术团队13 小时前
验证码识别实战:前端不写页面,改训模型了?
前端
MomentYY13 小时前
Temperature:AI 的“脑洞旋钮”
前端·llm·ai编程
远航_14 小时前
OpenSpec 完整详细介绍
前端·后端
召钱熏14 小时前
状态枚举正确≠渲染正确:一个语音按钮的状态机边界修复实录
android·前端