call/apply - 函数绑定作用域并返回执行结果

62 阅读1分钟

代码实现

/**
* @description: call/apply
* @author: huen2015
*/

// @ts-ignore
Function.prototype.call1 = function (context: any = window, ...args: any[]): any {
    let result
    // 设置唯一 key
    const fnKey = Symbol()
    // 将 fnKey-fn 设置为 context 的 key-value
    context[fnKey] = this
    // 执行函数
    result = context[fnKey](...args)
    // 函数执行完,删除新建的 key-value
    delete context[fnKey]

    return result
}

// @ts-ignore
Function.prototype.apply1 = function (context: any = window, args: any[]): any {
    if (typeof context !== 'object') {
        return this(...args)
    }

    let result
    // 设置唯一 key
    const fnKey = Symbol()
    // 将 fnKey-fn 设置为 context 的 key-value
    context[fnKey] = this
    // 执行函数
    result = context[fnKey](...args)
    // 函数执行完,删除新建的 key-value
    delete context[fnKey]

    return result
}

function fn(this: any, name: string) {
    return 'name:' + name + '-' + 'age:' + this.age
}
const obj = {
    age: 20
}

// @ts-ignore
const callResult = fn.call1(obj, 'call', 21)
// @ts-ignore
const applyResult = fn.apply1(obj, ['apply', 22])
console.log('callResult', callResult)
console.log('applyResult', applyResult)

代码演示仓库