手写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)
相关推荐
漂流瓶jz36 分钟前
Webpack中各种devtool配置的含义与SourceMap生成逻辑
前端·javascript·webpack
这是个栗子39 分钟前
【问题解决】用pnpm创建的 Vue3项目找不到 .eslintrc.js文件 及 后续的eslint配置的解决办法
javascript·vue.js·pnpm·eslint
前端架构师-老李1 小时前
React 中 useCallback 的基本使用和原理解析
前端·react.js·前端框架
木易 士心1 小时前
CSS 中 `data-status` 的使用详解
前端·css
明月与玄武1 小时前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
花姐夫Jun1 小时前
基于Vue+Python+Orange Pi Zero3的完整视频监控方案
vue.js·python·音视频
牧马少女2 小时前
css 画一个圆角渐变色边框
前端·css
zy happy2 小时前
RuoyiApp 在vuex,state存储nickname vue2
前端·javascript·小程序·uni-app·vue·ruoyi
小雨青年2 小时前
Cursor 项目实战:AI播客策划助手(二)—— 多轮交互打磨播客文案的技术实现与实践
前端·人工智能·状态模式·交互
Nan_Shu_6142 小时前
学习:JavaScript(5)
开发语言·javascript·学习