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);
相关推荐
猫3285 分钟前
echarts 日常问题解决
前端·javascript·echarts
新中地GIS开发老师8 分钟前
地信职业百科④:GIS开发工程师
前端·数据库·gis·webgis·三维gis开发
我是大卫17 分钟前
【图】React源码解析-从数据结构、调度器、源码设计模式到状态计算引擎,深挖useReducer原理
前端·react.js·源码
willes23 分钟前
列表中的倒计时组件
前端
LVZ25 分钟前
用了半年 AI 写代码,最烦的不是代码,是环境
前端·后端·开源
polaris_tl26 分钟前
一行 `compress: false`,为什么让 SSE 首包恢复实时返回
前端
海边的云28 分钟前
别再让 AI 瞎改代码:一套让大模型「收敛」的前端专家 Skill》
前端
kisshyshy28 分钟前
给端侧大模型装上“发动机”:React 合成事件 + 进度条组件全解
前端·react.js·node.js
hunterandroid39 分钟前
DataStore 工程化实践:迁移、并发更新与异常恢复
android·前端
晓说前端40 分钟前
TypeScript 核心语法进阶 —— 字面量类型与类型推论
前端·typescript