手写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)
相关推荐
陈随易4 小时前
在 VSCode 里,把项目一键部署到服务器
前端·后端·程序员
Highcharts.js4 小时前
教程:基于 React + Highcharts 构建一个单页应用程序、按需数据拉取与图表渲染
开发语言·前端·数据结构·react.js·前端框架·highcharts·页面应用
To_OC4 小时前
我被 useState 坑了两次之后,终于把它的脾气摸透了
前端·javascript·react.js
鱼樱前端4 小时前
我用 Claude Code 后,编码效率翻 3 倍。但更值钱的是别的。
前端·后端·ai编程
_lucas5 小时前
给知识库网站接入AI问答
前端·ai编程·全栈
前端糕手5 小时前
前端面试题大全:JavaScript + Vue3 + React + TypeScript + 工程化 + 性能优化
前端
我不叫武6 小时前
一个用 Rust 写的离线编码查询桌面工具
前端
Web4Browser7 小时前
指纹浏览器 API 自动化怎么接:启动 Profile、获取 CDP 端点并连接自动化框架
前端·网络·typescript·自动化
Patrick_Wilson8 小时前
从 React 到 Flutter:写给前端的一张跨端知识地图
前端·flutter·react.js
颜酱8 小时前
06 | 把 meta_config 同步进 MySQL(生成阶段)
前端·人工智能·后端