全局对象属性转换成临时变量,提升读取效率css
document = window.document
采用 call 保证类型与方法一致数组
// zepto var emptyArray = [] $.inArray = function(elem, array, i){ return emptyArray.indexOf.call(array, elem, i) } // 原生 $.inArray = function(elem, array, i){ // 此时若是 array 不是 数组类型,则会报错: // array.indexOf is not a function return array.indexOf(elem, i) }
判断变量可能的值函数
/complete|loaded|interactive/.test(document.readyState) // 简洁高效 // 常规写法 document.readyState=='complete' || document.readyState=='loaded' || document.readyState=='interactive'
$.map
& $.each
var uniq = function (array){ return filter.call(array, function (item, idx) { return array.indexOf(item) == idx }) }
function extend(target, source, deep) { for (key in source) if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) target[key] = {} if (isArray(source[key]) && !isArray(target[key])) target[key] = [] extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] }
['width', 'height'].forEach(function(dimension){ var dimensionProperty = dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){ var offset, el = this[0] if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] else return this.each(function(idx){ el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } })