Skip to content

为什么要函数柯里化(场景)

  1. 参数不方便传递
javascript

function a(b) {}

// 函数a的参数,不方便直接传递
// 直接a(123)是函数调用,但是then里面需要的是一个函数
new Promise().then(a.bind(123))
  1. 有些参数是固定的
javascript

// 假设inputTest是一个表单校验的函数
// 第一个参数是校验的正则,第二个参数是表单的值
// 现在有10个表单的校验规则是一样的,即reg参数是一样的
function inputTest(reg, value) {}

// 柯里化固定参数
const numberTest = inputTest.bind(this, /^[0-9]$/)
numberTest(123)

柯里化的实现

柯里化函数接收一个固定参数,然后返回函数里面再接受一个固定参数

javascript

function aCurry(num1) {
    return function(num2) {
    }
}

function a(num1, num2) {}

aCurry(num1)(num2)

bind的手写实现

javascript

Function.prototype.myBind = function(thisArg) {
    if(typeof this!=='function') return
    var _self = this
    var args = Array.prototype.slice.call(arguments, 1)
    return function() {
        return _self.apply(thisArg, args.concat(Array.prototype.slice(arguments)))
    }
}