zepto 源碼分析2

優化技巧

  • 全局對象屬性轉換成臨時變量,提升讀取效率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

  • 對原生 map & forEach 的拓展,使支持對象
  • $.map 會過濾 null 值
  • $.map 支持類數組對象,如函數中的 arguments
  • $.each 在返回值爲 false 時,能停止數組遍歷

數組去重

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]
}

獲取元素的寬高

  • 計算 window 寬高用 innerWidth / innerHeight
  • 計算 document 寬高用 scrollWidth / scrollHeight
  • 其餘元素:getBoundingClientRect,返回數值對象包含left、top、right和bottom,單位爲 px
['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]()))
    })
  }
})
相關文章
相關標籤/搜索