function add(x, y){ return x + y } add(1, 2) // 3
function sayInfo(name){ return function (age){ console.log(`${name}今年${age}岁`) } } const johnAge = sayInfo(‘John‘) // 等价于====> const johnAge = function (age){console.log(`John今年${age}岁`)} const tomAge = sayInfo(‘Tom‘) // 等价于====> const tomAge = function (age){console.log(`Tom今年${age}岁`)} johnAge(‘12‘) // John今年12岁 johnAge(‘13‘) // John今年13岁 tomAge(‘22‘) // Tom今年22岁 tomAge(‘22‘) // Tom今年23岁
如果不用柯里化应该是这样写代码:
function sayInfo(name, age){ console.log(`${name}今年${age}岁`) } sayInfo(‘John‘, ‘12‘) // John今年12岁 sayInfo(‘John‘, ‘13‘) // John今年13岁 sayInfo(‘Tom‘, ‘22‘) // Tom今年22岁 sayInfo(‘Tom‘, ‘22‘) // Tom今年23岁
在这里看起来柯里化的代码反而显得冗余。其实不然, 下面看一个适合使用柯里化的场景。↓
// 判断变量val是否是数组 if(Object.prototype.toString.call(val).slice(8, -1) === ‘Array‘){ ... } // 判断变量val是否是对象 if(Object.prototype.toString.call(val).slice(8, -1) === ‘Object‘){ ... }
2.柯里化产生不同函数:
// 上述代码判断使用的是同一个方法。可以用柯里化封装成不同函数 const isType = function (type) { return function (val){ return type === Object.prototype.toString.call(val).slice(8, -1) } } const isArray = isType(‘Array‘) const isObject = isType(‘Object‘)
3.使用:
// 由此,判断逻辑就改成如下形式 if(isArray(val)){ ... } if(isObject(val)){ ... } // 修改后的代码精致了不少,不是吗?
const isType = type => val => type === Object.prototype.toString.call(val).slice(8, -1) // 箭头函数写法 const isArray = isType(‘Array‘) // 是否数组 const isObject = isType(‘Object‘) // 是否对象 const isNull = isType(‘Null‘) // 是否null const isUndefined = isType(‘Undefined‘) // 是否undefined const isFunction = isType(‘Function‘) // 是否函数 const isRegExp = isType(‘RegExp‘) // 是否正则 const isString = isType(‘String‘) // 是否字符串 const isNumber = isType(‘Number‘) // 是否数字 const isDate = isType(‘Date‘) // 是否日期
原文:https://www.cnblogs.com/jxjl/p/12825258.html