手写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)
相关推荐
GISer_Jing1 小时前
Three.JS渲染架构解读
java·javascript·架构
发现一只大呆瓜2 小时前
超全 Vite 性能优化指南:网络、资源、预渲染三维落地方案
前端·面试·vite
IT_陈寒2 小时前
Vue的computed属性怎么突然不更新了?
前端·人工智能·后端
时寒的笔记2 小时前
day13~14核心案例某采招网
开发语言·javascript·ecmascript
智商不够_熬夜来凑2 小时前
【Picker】单选多选
前端·javascript·vue.js
米饭不加菜3 小时前
Typora 原生流程图语法完全指南(Flowchart.js)
前端·javascript·流程图
scan7243 小时前
langgraphy条件边
前端·javascript·html
冰小忆3 小时前
类变量在继承场景下的初始化规则是怎样的?
java·前端·数据库
用户938515635073 小时前
《JS 对象知识地图:10 个小节,从字面量到原型链全覆盖》
javascript
YAwu114 小时前
JavaScript this 底层机制剖析
前端·javascript