柯理化

柯理化代码演示

function checkAge (age) {
  let min = 18
  return age >= min
}


// 普通的纯函数
function checkAge (min, age) {
  return age >= min
}

柯理化就是讲多个参数转化为几个分开的参数

// 函数的柯里化
function checkAge (min) {
  return function (age) {
    return age >= min
  }
}

// ES6
let checkAge = min => (age => age >= min)

let checkAge18 = checkAge(18)
let checkAge20 = checkAge(20)

console.log(checkAge18(20))
console.log(checkAge18(24))

实现一个柯理化函数

// 生成柯理化函数
function curry(func) {
    return function curriedFn(...args) {
        // 判断函数的参数是否与形参相等
        if (args.length < func.length) {
            return function () {
                // 递归组合参数
                return curriedFn(...args.concat(Array.from(arguments)));
            }
        }
        // 相等则直接执行函数
        return func(...args);
    }
}

function getSum(a, b, c) {
    return a + b + c;
}
let curried = curry(getsum)
curried(1, 2, 3)
curried(1)(2)(3)
curried(1, 2)(3)

函数对象中有很多用到柯理化如 函数中的延迟执行方法  bind

实现mybind

// bind

function fn(a, b, c) {

}
/**
 * context 上下文对象
 */
const f = fn.bind(context, 1, 2)
f(3)

Function.prototype.mybind = function (context, ...args) {
    return (...rest) => this.call(context, ...args, ...rest,)
}

实现mycall

function fn(a, b, c) {
    console.log(this)
    return a + b + c
}
const obj = {
    name: 'xxx'
}
fn.call(obj,1,2,3)
Function.prototype.mycall = function (context, ...args) {
    // 如果对象上下文为null,则赋值window
    context = context || window
    context.fn = this
    const relust = context.fn(...args)
    delete context.fn
    return relust
}

fn.mycall(obj,1,2,3)

这样可以实现,但是会打印出赋值的操作

可以用Object.defineProperty操作,使之不能打印出来

Function.prototype.mycall = function (context, ...args) {
    // 如果对象上下文为null,则赋值window
    context = context || window
    Object.defineProperty(context, "fn", {
        enumerable: false,//不可被枚举
        value: this
    })
    const relust = context.fn(...args)
    delete context.fn
    return relust
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值