使用Object.prototype.toString配合闭包,通过传入不同的判断类型来返回不同的判断函数,一行代码,简洁优雅灵活。

ES6的实现方法

  1. const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target);
  2. // 使用
  3. const isArray = isType('Array');
  4. isArray([]); // true

ES5的实现方法

  1. function isType(type) {
  2. return function(target) {
  3. return "[object " + type + "]" === Object.prototype.toString.call(target);
  4. }
  5. };
  6. // 使用
  7. const isObject = isType('Object');
  8. isObject({}); // true

结论

需要注意的是这个函数不能用来检测可能会产生包装类型的基本数据类型上,因为call方法始终会将第一个参数进行装箱操作,导致基本类型和包装类型无法区分。