1 类型判断
KISSY封装了 几个判别函数, KISSY.isXxx形式的:
isDate isEmptyObject isFunction isNull isNumber isObject isPlainObject isRegExp isString isUndefined isWindow
它们形式一致,所以能不能合并成一个函数呢?像下面这样调用:
is(new Date,'date') is([],'array')
答案是可以的:
// -*- coding: utf-8; -*- function is(o, type) { var isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1} type = type.toLowerCase(); // {"NaN": 1, "Infinity": 1, "-Infinity": 1}.hasOwnProperty(2) -> false // {"NaN": 1, "Infinity": 1, "-Infinity": 1}.hasOwnProperty(NaN) -> true if (type == "finite") { return !isnan["hasOwnProperty"](+o); } if (type == "array") { return o instanceof Array; } return (type == "null" && o === null) || // is(undefined,'undefined') (type == typeof o && o !== null) || // Object(Object) == Object -> true // Object({}) == {} -> false (type == "object" && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || Object.prototype.toString.call(o).slice(8, -1).toLowerCase() == type; } /// [] is 'array' and 'object' console.log(is([],'array')) // -> true console.log(is([],'object')) // -> true console.log(is({},'object')) // -> true console.log(is(Function,'object')) // -> true console.log(is(new Function(),'object')) // -> true console.log(is(new Function(),'function')) // -> true console.log(is(Error,'object')) // -> true console.log(is(new Error,'error')) // -> true console.log(is(Date,'object')) // -> true console.log(is(new Date,'date')) // -> true /// Infinity(无限)当然不是有限(finite)的啦 console.log(is(Infinity,'finit')) // -> false /// 判定一个数是否有限finite console.log(is(22,'finite')) // -> true console.log(is("a short string",'string')) // -> true console.log(is(10,'number')) // -> true console.log(is(null,'null')) // -> true console.log(is(undefined,'undefined')) // -> true console.log(is(true,'boolean')) // -> true console.log(is(false,'boolean')) // -> true console.log(is(/\\/,'regexp')) // -> true
通过上面的测试可知,除了isEmptyObject、isisPlainObject和isWindow,其它的都包含到一个函数里面去了,而且还额外提供判断boolean、finite类型判断
2 备注
上面的代码是从raphael.js中抽取出来的,原作者v5