手写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)
相关推荐
We་ct6 分钟前
LeetCode 137. 只出现一次的数字 II:从基础到最优的两种解法详解
前端·数据结构·算法·leetcode·typescript·位运算
源码站~7 分钟前
基于Spring Boot+Vue3的烹饪交流学习系统 设计与实现
java·vue.js·spring boot·后端·mysql·毕业设计·毕设
星空8 分钟前
前端--A_3--HTML区块_块元素与行内元素
前端·html
如意猴10 分钟前
【前端】001 前端初识——数字世界的门面
前端
Dxy123931021614 分钟前
如何使用 ECharts 绘制 K 线图
开发语言·javascript
不会写DN16 分钟前
Protocol Buffers(.proto)实战入门:Go 生态最常用的接口定义语言
java·前端·golang
小小小米粒20 分钟前
原生 JS:数据和视图「分离」,必须手动同步原生 JS 里,数据是数据,视图是视图,两者完全没关系
前端·javascript·vue.js
摸鱼仙人~23 分钟前
纯前端 Vue 实现共享预览链接方案
前端·javascript·vue.js
happymaker062624 分钟前
VueCli标准化工程中的组件通信操作
开发语言·前端·javascript