手写call、apply、bind

一、手写call

javascript 复制代码
const person = {name:'zhangsan'}
function foo(numA,numB){
    console.log(this)
    console.log(numA,numB)
    return numA + numB
}

// 手写call
Function.prototype.mycall = function(thisArg,...args){ // 手写call
    const key = Symbol('key') // 唯一标识符
    thisArg[key] = this // 绑定this
    const res = thisArg[key](...args) // 展开参数
    delete thisArg[key] // 清除
    return res
}

const res = foo.mycall(person,1,2) // thisArg = person
console.log(res)

二、手写apply

javascript 复制代码
Function.prototype.myapply = function(thisArg,args){
    const key = Symbol('key')
    thisArg[key] = this
    const res = thisArg[key](...args)
    delete thisArg[key]
    return res
}

const person = {name:'zhangsna'}
function foo(numA,numB){
    console.log(this)
    console.log(numA,numB)
    return numA+numB
}
const res = foo.myapply(person,[1,2])
console.log(res)

三、手写bind

javascript 复制代码
// 手写bind
Function.prototype.myBind = function(thisArg,...args){
    // 返回新函数
    return (...reArgs)=> this.call(thisArg,...args,...reArgs)
}

const person = {name:'zhangsan'}
function foo(numA,numB,numC,numD){
    console.log(this)
    console.log(numA,numB,numC,numD)
    return numA + numB + numC + numD
}
const bindFunc = foo.myBind(person,1,2)
const res = bindFunc(3,4)
console.log(res)
相关推荐
李游Leo4 分钟前
HarmonyOS 7 ArkTS + ohpm:三方 JS 库副作用隔离与 API 26 升级回归【鸿蒙心迹】
javascript·回归·harmonyos
你挚爱的强哥9 分钟前
【sgKeyboard】自定义组件:虚拟键盘
前端·javascript·计算机外设
锅里游的鱼吖15 分钟前
echarts自定义折线图
前端·javascript·数据库
hunteritself33 分钟前
卷卷卷!GPT-6 Sol、Luna 正式发布,OpenAI 开始卷价格了
大数据·前端·人工智能·深度学习·transformer
何何____1 小时前
Vue 全局事件总线详解
前端·javascript·vue.js
涉密IT资质笔记2 小时前
涉密人员脱密期管理规范:期限分级模型、就业限制边界与违规认定标准
java·服务器·前端·网络·数据库
EatFan2 小时前
Go语言全栈实战:基于 Gin + Vue + JWT + RBAC 从零搭建前后端分离权限管理系统
vue.js·golang·go·vue·gin·jwt·rbac
u0111026752 小时前
工具页案例图如何编写 alt让图片说明与处理场景对应
java·前端·javascript·图像处理·人工智能·算法·ai作画
事圆则缓2 小时前
Flutter 状态管理框架对比(五):GetX 的响应式、依赖注册与生命周期
前端·javascript·flutter
广州智造3 小时前
Radioss复合材料使用的单元属性
前端·设计·cad·建模·cae·radioss