JS中实现函数柯里化

1.概念

一个函数可以接受多个参数,反复被调用,例fn(1,2,3,4,5)(6,7)(8,9,10),该技术被命名为函数柯里化。

2.示例

需求:求和fn(1,2,3,4,5)(6,7)(8,9,10)
代码:

 function currying() { //12345
            // arguments 伪数组 ,具备数组的属性,但是不包含数组的方法
            const args = Array.prototype.slice.call(arguments);
            // const args = []._proto_.slice.call(arguments); 
            // Array.prototype.slice 是原型上的一个方法
            // call 改变this指向
            // 数组方法依赖于内部是this数据容器来执行
            // console.log(args);


            // 一个函数访问外部变量,形成闭包
            const inner = function () { //67 8910
                // args
                args.push(...arguments)
                return inner
            }
            // inner函数toString改不了,改一个计算原始数据类型的方式
            inner.__proto__[Symbol.toPrimitive]= inner.toString=inner.getValue = function () {
                return args.reduce((num1, num2) => {
                    return num1 + num2
                }, 0)
            }
            return inner;
        }
        let res = currying(1, 2, 3, 4, 5)(6, 7)(8, 9, 10)
        // let sum = res.getValue()
        // console.log(sum);

        // 可以允许将返回值二次计算
        console.log(res-1);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

对卦卦上心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值