var isString = function(obj) {
return Object.prototype.toString.call(obj) === '[object, String]';
}
var isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object, Array]';
}
var isNumber = function(obj) {
return Object.prototype.toString.call(obj) === '[object, Number]';
}
var isType = function(type) {
return function(obj) {
Object.prototype.toString.call(obj) === `[object ${type}]`;
}
}
var isString = isType('String');
var isArray = isType('Array');
var isNumber = isType('Number');
终极方案:
var Type = {};
for (var i = 0, type; type = ['String', 'Array', 'Number'][i++];) {
(function(type){
Type[`is${type}`] = function(obj) {
return Object.prototype.toString.call(obj) === `[object ${type}]`;
};
})(type)
}
Type.isArray([]); // true
Type.isString('str'); // true
网友评论