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);
相关推荐
木斯佳30 分钟前
前端八股文面经大全:快手电商日常实习前端一面(2026-05-15)·面经深度解析
前端·面试·面经
2601_958492558 小时前
Optimizing Engagement with Freehead Skate - HTML5 Game - Construct 3
前端·html·html5
茉莉玫瑰花茶8 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
zhangxingchao9 小时前
AI应用开发六:企业知识库
前端·人工智能·后端
山峰哥9 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
红尘散仙9 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying9 小时前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙10 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang45310 小时前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端