isType方法封装和类型检测

isType封装

任何的数据类型,都会包含一个叫做toString的方法存在他们的骨子里。这个方法就是将数据由其他的形态转换成string形态(除了null和undefined),所以我们可以利用该特性做类型检测。

console.log(toString.call('aa')); // [object String]
console.log(toString.call(1234)); // [object Number]
console.log(toString.call(true)); // [object Boolean]
console.log(toString.call(Math)); // [object Math]
console.log(toString.call(new Date())); // [object Date]
console.log(toString.call(function aa(){})); // [object Function]
console.log(toString.call([])); // [object Array]
console.log(toString.call({})); // [object Object]
// 是不是字符串的方法可以封装如下
var isString = function(obj){
    return toString.call(obj) == '[object String]';//注意String是大写
}

// 是不是函数
var isFunction = function(obj){
    return toString.call(obj) == '[object Function]';
}
 
// 是不是数组
var isArray = function(obj){
    return toString.call(obj) == '[object Array]';
}

...写到这里,我想你就明白,都是利用最上面的特性进行判断

可以发现除了类型不一样,其他都一样,我们就想着能不能想封装成一个函数,把他们公共的部分都抽离出来,所以封装如下:

var isType = function(type) {
	return function(obj) {
		return toString.call(obj) == '[object ' + type + ']'; //注意,object后面有空格
	}
}

类型检测也可以用以下函数

function typeOf(ele) {
	var r;
	if(ele === null) r = null;
	else if(ele instanceof Array) r = 'Array';
	else if(ele === window) r = 'window';
	else if(ele instanceof Date) r = 'Date';
	else r = typeof ele;
	return r;
}
原文地址:https://www.cnblogs.com/bonly-ge/p/9556637.html