使用Object.prototype.toString()对内置类型进行常规类型检查

时间:2014-10-27 18:49:28

标签: javascript typechecking

我想知道使用Object.prototype.toString()来进行内置类型的一般类型检查是否合适。我有一个看起来像这样的函数:

// Return the built-in type of an object.
var typeOf = (function() {
  var reType = /\[object (\w+)\]/; 
  return function typeOf(obj) {
    return reType.exec(Object.prototype.toString.call(obj))[1];
  };
})();

调用该函数会返回以下结果:

console.log( typeOf(null) );         // => Null
console.log( typeOf(undefined) );    // => Undefined
console.log( typeOf([]) );           // => Array
console.log( typeOf(true) );         // => Boolean
console.log( typeOf(new Date()) );   // => Date
console.log( typeOf(new Error()) );  // => Error
console.log( typeOf(function(){}) ); // => Function 
console.log( typeOf(1) );            // => Number
console.log( typeOf({}) );           // => Object
console.log( typeOf(/ /) );          // => RegExp
console.log( typeOf("") );           // => String

除了可能比其他形式的类型检查更慢的事实之外,这是否可以接受?

我问的原因之一是因为我想为我正在处理的项目编码和序列化对象的内置类型。我正在寻找将返回的类型传递给返回数字代码的函数:

// Encode a built-in type as a number.
var encodeType = (function() {
  var types = {
    'Null':      0,
    'Undefined': 1,
    'Array':     2,
    'Boolean':   3,
    'Date':      4,
    'Error':     5,
    'Function':  6,
    'Number':    7,
    'Object':    8,
    'RegExp':    9,
    'String':    10,
    'Arguments': 11,
    'Math':      12,
    'JSON':      13
  };
  return function encodeType(type) {
    return types[type];
  }
})();

因此输出变为:

console.log(encodeType( typeOf(null) ));         // => 0
console.log(encodeType( typeOf(undefined) ));    // => 1
console.log(encodeType( typeOf([]) ));           // => 2
console.log(encodeType( typeOf(true) ));         // => 3
console.log(encodeType( typeOf(new Date()) ));   // => 4
console.log(encodeType( typeOf(new Error()) ));  // => 5
console.log(encodeType( typeOf(function(){}) )); // => 6
console.log(encodeType( typeOf(1) ));            // => 7
console.log(encodeType( typeOf({}) ));           // => 8
console.log(encodeType( typeOf(/ /) ));          // => 9
console.log(encodeType( typeOf("") ));           // => 10

这种类型检查有任何陷阱吗?感谢您的任何见解。

2 个答案:

答案 0 :(得分:3)

以下是underscore.js'实施:

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) === '[object ' + name + ']';
    };
  });

是的,这种方法很好。

P.S。 toString是上述代码中Object.prototype.toString的缩写。

答案 1 :(得分:0)

我不明白所有额外的语法。这不是完全相同的事吗?

var typeOf = function(obj) {
    var reType = /\[object (\w+)\]/;
    return reType.exec(Object.prototype.toString.call(obj))[1];
    };

此外,为encodeType

使用开关可能更好