SOURCE

/**
 * 手写call方法
 * 1、定义mycall方法
 * 2、设置this并调用原函数
 * 3、接受剩余参数并返回结果
 */

Function.prototype.myCall = function(thisArg,...arg){
    // thisArg为传入的设置为this的对象
    // this原函数(原函数.myCall)
    // 使用Symbol确保函数名的唯一性,防止与传入的值重名
    const key = Symbol('key')
    thisArg[key] = this
    const res = thisArg[key](...arg)
    delete thisArg[key]
    return res
}

// 示例
const person = {
    name:'call手写'
}

function func(numA,numB){
    return numA + numB
}

const res = func.myCall(person,6,7)
console 命令行工具 X clear

                    
>
console