在Zepto里面有一些沒有暴露出來的私有方法咱士,有一些值得借鑒的地方立由,比如里面用來判斷類型的type函數(shù)。大概紀(jì)錄如下:
一些類型判斷方法
判斷數(shù)組:
isArray = Array.isArray ||
function(object){ return object instanceof Array }
類型判斷函數(shù)
var class2type = {},
toString = class2type.toString;
// class2type map
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase()
});
function type(obj) {
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
}
上面的類型判斷序厉,基本上可以判斷所有的類型锐膜。主要是改變toString的this指向來實(shí)現(xiàn)的。
是否是函數(shù)弛房,對象(用了上面的type方法):
function isFunction(value) { return type(value) == "function" }
function isObject(obj) { return type(obj) == "object" }
判斷Window,Document節(jié)點(diǎn)
function isWindow(obj) { return obj != null && obj == obj.window }
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
判斷是否是 plainObject(就是通過{}和new Object聲明出來的空對象吧)
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
判斷是是不是類數(shù)組
function likeArray(obj) { return typeof obj.length == 'number' }
數(shù)組方法及利用
提取了3個數(shù)組的方法concat
,filter
,slice
var emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice;
用filter來過濾數(shù)組中的空項(xiàng):
function compact(array) { return filter.call(array, function(item){ return item != null }) }
刪除數(shù)組中重復(fù)的元素 *
uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }