标签:
文章首发: http://www.cnblogs.com/sprying/p/4349426.html
本文罗列了一般Js类型检测的方法,是构建Js知识体系的一小块,这篇文章是我很早之前总结的。
var obtainType = function(o){
var t;
if(o === null ) return “null”;
else if(o !== o) return “NaN”;
else if( (t = typeof o) !== ‘object’) return t;
}
function obtainType(type) {
return function (obj) {
return Object.prototype.toString.call(obj) === "[object " + type + "]"
}
}
var isObject = isType("Object")
var isString = isType("String")
var isArray = Array.isArray || isType("Array")
var isFunction = isType("Function")
/**
* 返回函数的名字,可能为空串;不是函数,返回null
*/
Function.prototype.getName = function () {
if ("name" in this) return this.name;
return this.name = this.toString().match(/function\s*([^(]*)\(/)[1];
};
/**
* 返回:null NaN undefined string number boolean
* function Array String Object(包括一些自定义类型) 自定义类型
*/
var obtainType =function(o){
/**
* 获取参数类型
* 对象直接量、Object.create、自定义构造函数的类属性皆为Object;
* 识别出原生类型 (内置构造函数和宿主对象)
*/
function classOf(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
/**
* 返回函数的名字,可能为空串;不是函数,返回null
*/
Function.prototype.getName = function () {
if ("name" in this) return this.name;
return this.name = this.toString().match(/function\s*([^(]*)\(/)[1];
};
var t, c, n;
// 处理null值特殊情形
if (o === null) return "null";
// NaN:和自身值不相等
if (o !== o) return "NaN";
// 识别出原生值类型和函数、undefined
if ((t = typeof o) !== "object") return t;
// 识别出原生类型
if ((c = classOf(o)) !== "Object") return c;
// 返回自定义类型构造函数名字
if (o.constructor && typeof o.constructor === "function" &&
(n = o.constructor.getName()))
return n;
return "Object";
};
5.
var strObj = new String(‘abc‘); typeof strObj // "object" obtainType(strObj) // "String"
// bad
if (name !== ‘‘) {
// ...stuff...
}
// good
if (name) {
// ...stuff...
}
// bad
if (collection.length > 0) {
// ...stuff...
}
// good
if (collection.length) {
// ...stuff...
}
标签:
原文地址:http://www.cnblogs.com/sprying/p/4349426.html