让前端飞jsWeb前端之路

isType(判断数据类型进行封装)

2019-06-10  本文已影响1人  CRUD_科科

判断数据类型的方式

我们常见的可以判断数据类型的方法有:typeof、instanceof(__ proto __)、constructor。以上方法都有缺陷,缺陷就不在赘述,最好的方法是console.log(Object.prototype.toString.call === '[object object]')。

通过Object.prototype.toString.call() 对数据类型检测进行封装

// 通过Object.prototype.toString.call() 对数据类型检测进行封装
var a = '213'
function isType(data,type) {
  return Object.prototype.toString.call(data) === `[object ${type}]`
}
console.log(isType(a,'String'))

但是我们发现这样封装有很大的缺陷,第二个参数一旦输错,比如写成了小写,那么返回的结果就变成了false,我们为了解决这个问题,就用到了批量生产函数的方法:

function isType(type) { // 函数柯里化(偏函数) 一个函数一个参数
  return function(data) {
    return Object.prototype.toString.call(data) === `[object ${type}]`;
  }
}

let objs = {};

['Null',
  'Undefined',
  'Object',
  'Array',
  'String',
  'Number',
  'Boolean',
  'Function',
  'RegExp'
].forEach(type => {  // 批量生产函数
  objs['is' + type] = isType(type);
})

console.log(objs.isString('213'));  // true
console.log(objs.isObject({}));  // true
console.log(objs.isFunction(Function));  // true
上一篇 下一篇

猜你喜欢

热点阅读