由于js自带的typeof不够详细,所以我们自己封装一个。
function type(target) {
var template = {
"[object Array]" : "Array",
"[object Object]" : "Object",
"[object Number]" : "Number - object",
"[object Boolean]" : "Boolean - object",
"[object String]" : "String - object"
}
var ret = typeof(target);
if(target === null){
return "null";
}else if(ret == "object") {
var str = Object.prototype.toString.call(target);
return template[str];
}else{
return ret;
}
}
通过Object原型链上的toString方法来进行跟好多判断,因为数组,对象,包装类在调用toString时,各自在原型链上重写了toString方法。