typeof
在这种情况下不要使用。有几个原因是有问题的:
typeof null // 'object'
typeof [] // 'object'
typeof 'foo' // 'string'
typeof new String('foo') // 'object'
'foo' == new String('foo') // true
相反,使用Object::toString
:
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call('foo') // '[object String]'
Object.prototype.toString.call(new String('foo')) // '[object String]'
装饰师将满足您的要求:
var getType = function(value) {
return Object.prototype.toString.call(value)
.replace(/^\[object |\]$/g, '').toLowerCase();
};
var checkTypes = function(types, fn) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
for (var idx = 0; idx < types.length; idx += 1) {
var expected = types[idx];
var received = getType(args[idx]);
if (received != expected) {
throw new TypeError('expected ' + expected + '; received ' + received);
}
}
fn.apply(null, args);
};
};
var exampleUsage = checkTypes(['array', 'array', 'number'], function(arr1, arr2, num1) {
console.log('arr1:', arr1);
console.log('arr2:', arr2);
console.log('num1:', num1);
});
使用示例:
exampleUsage([], [], 0);
// arr1: []
// arr2: []
// num1: 0
exampleUsage([], [], 'foo');
// TypeError: expected number; received string