手写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)
相关推荐
Ten peaches31 分钟前
Selenium-Java版(环境安装)
java·前端·selenium·自动化
Enti7c33 分钟前
BOM知识点
javascript
心.c43 分钟前
vue3大事件项目
前端·javascript·vue.js
姜 萌@cnblogs1 小时前
【实战】深入浅出 Rust 并发:RwLock 与 Mutex 在 Tauri 项目中的实践
前端·ai·rust·tauri
蓝天白云下遛狗1 小时前
google-Chrome常用插件
前端·chrome
多多*2 小时前
Spring之Bean的初始化 Bean的生命周期 全站式解析
java·开发语言·前端·数据库·后端·spring·servlet
linweidong2 小时前
在企业级应用中,你如何构建一个全面的前端测试策略,包括单元测试、集成测试、端到端测试
前端·selenium·单元测试·集成测试·前端面试·mocha·前端面经
满怀10152 小时前
【HTML 全栈进阶】从语义化到现代 Web 开发实战
前端·html
繁依Fanyi2 小时前
用 UniApp 构建习惯打卡 App —— HabitLoop 开发记
javascript·uni-app·codebuddy首席试玩官
东锋1.32 小时前
前端动画库 Anime.js 的V4 版本,兼容 Vue、React
前端·javascript·vue.js