手写Function.call,apply,bind函数

博客介绍了扩展运算符相关前置知识,动手实现三个函数时,其实现依赖扩展运算符,提出可通过 Function 构造函数避免使用该运算符,还给出了代码转载来源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前置知识

问腿

动手实现了这三个函数,然而问题在于实现依赖了 ... 运算符,也许可以通过 Function 构造函数来避免使用 ... 运算符。

代码


Function.prototype.myCall = function(context, ...args) {
    if (typeof this !== 'function') {
        throw new TypeError('Error');
    }
    if (context === undefined) context = window || global; // 适配浏览器,nodejs环境    
    context.__fn = this;
    context.__fn(...args);
};

Function.prototype.myApply = function(context, argsArray) {
    // 对传进来的参数数组调用扩展运算符... 然后直接调用myCall函数
    return this.myCall(context, ...argsArray);
};

Function.prototype.bind = function(context, ...bindedArgs) {
    return (...newArgs) => this.call(context, ...bindedArgs, ...newArgs);
}

function test() {
    // 测试用例
    try {
        window.testStr = '全局环境';
    } catch (err) {
        global.testStr = '全局环境';
    }
    
    
    const foo = {
        testStr: '对象调用',
        run (...args) {
            console.log(`testStr: ${this.testStr} args: ${args}`);
        }
    }
    const run = foo.run;

    foo.run(1, 2, 3);
    run(1, 2, 3);
    run.myCall(foo, 1, 2, 3);
    console.log('test call --------------');

    foo.run(1, 2, 3);
    run(1, 2, 3);
    run.myApply(foo, [1, 2, 3]);
    console.log('test apply --------------');

    const bindedRun = run.bind(foo, 'bindedArg');
    foo.run(1, 2, 3);
    run(1, 2, 3);
    bindedRun(1, 2, 3);
    console.log('test bind --------------');
    
    
} 

test();
复制代码

转载于:https://juejin.im/post/5cd03327f265da036706bdc5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值