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);
相关推荐
map_3d_vis1 小时前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
不要试图纠正别人2 小时前
构建 0 报错,产物体积翻倍:换引擎最容易漏的对账
前端·javascript
恋猫de小郭2 小时前
Android Keep Rules 解读,直接影响 Google Play 上架和曝光
android·前端·flutter
Hilaku2 小时前
面了 30 家公司拿到 2 个 Offer!
前端·javascript·程序员
延晗2 小时前
【从零开始 DeepSeek Harness 插件开发教程】三、从零开发 DeepSeek Harness 插件——完成第一个插件的挂载与运行
前端·人工智能
择势3 小时前
iOS 工程环境绝对隔离实践:开发机的"编不出"生产包
前端
某哈压力大3 小时前
Vue的双向绑定与自定义组件的v-model
前端·面试
CappuccinoRose3 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
天天鸭3 小时前
前端转全栈,要学会后端看项目的思维
前端·后端·ai编程
oil欧哟3 小时前
AI Agent 常用操作入门:独立目录、Plan 模式与跨话题交接指南
前端