常用的校验类型方法和特点
- typeof 不能校验 对象 数组 null
- instanceof 谁是谁的实例
- Object.prototype.toString.call 不能判断实例
- constructor 判断当前是谁的构造函数
简单实现checkType
function checkType(type,value){ return Object.prototype.toString.call(value) === `[object ${type}]` } // 使用 let res = checkType('String','123');
使用高阶函数实现
这个checkType函数返回的函数和传入的type组成了一个闭包函数,是传入的type在另一个函数中使用
function checkType(type){ return function(value){ return Object.prototype.toString.call(value)===`[object ${type}]` } } // 使用 let isString = checkType('String'); let isNumber = checkType('Number'); console.log(isString('123'));
柯里化实现
- 如果一下想不到怎么实现柯里化函数的额写法,就考虑能不能分步骤传递参数
- 提前把部分参数传递进去,返回一个新的函数,等待参数够达到执行条件的时候在执行
// 验证函数 function checkType(type,value){ return Object.prototype.toString.call(value) === `[object ${type}]`; } // 通用柯里化函数 function curring(fn,arr =[]){ let len = fn.length; // 代表fn需要传入参数的个数 return function(...args){ arr = [...arr, ...args]; if(arr.length < len ){ // 传入的参数达不到执行条件,递归继续接受参数 return curring(fn,arr); }else{ return fn(...arr); } } } // 生成验证函数 let util = {}; let types = ['String', 'Number', 'Boolean', 'Null', 'Undefined']; types.forEach(type => { util[`is${type}`] = curring(checkType)(type); }) console.log(util.isString('hello'))
柯里化概念
- 从函数结构上来看是函数返回函数,也是高阶函数;
- 从作用上来说是把接受多个参数变成接受单一参数;
- 从意义上来说是把核心功能提出一个更细小的函数;
- 从执行的过程来看是把函数参数收集起来,等待执行时机到了在执行,也就是惰性求值。
闭包概念
- 当前这个函数可以不在当前作用域(声明时)下执行