手写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)
相关推荐
王六岁5 分钟前
🐍 前端开发 0 基础学 Python 入门指南:数字与字符串篇
前端·python·全栈
over69719 分钟前
JavaScript恋爱物语:当代码学会送花,对象字面量也能当红娘!
javascript
tiantian_cool24 分钟前
HarmonyOS 开发环境配置指南 - macOS 版
前端
写不来代码的草莓熊43 分钟前
vue前端面试题——记录一次面试当中遇到的题(10)
前端·vue.js·面试
tiantian_cool1 小时前
正确的 .gitignore 配置
前端·github
三小河1 小时前
封装 classNames:让 Tailwindcss 类名处理更优雅
前端·javascript
起这个名字1 小时前
ESLint 导入语句的分组排序
前端·javascript
踩着两条虫1 小时前
VTJ.PRO低代码快速入门指南
前端·低代码
Lazy_zheng1 小时前
一场“数据海啸”,让我重新认识了 requestAnimationFrame
前端·javascript·vue.js
crary,记忆1 小时前
MFE: React + Angular 混合demo
前端·javascript·学习·react.js·angular·angular.js