1. 程式人生 > >學習源碼第三天(短暫的堅持)

學習源碼第三天(短暫的堅持)

art rdquo urn undefine 兩個 check 數組賦值 clas ati

/* 給JQuery原型添加屬性和方法 */
  jQuery.fn = jQuery.prototype = {
    // The current version of jQuery being used
    jquery: core_version,  //版本

    constructor: jQuery,   //添上constructor 指向構造函數,修復constructor
    init: function(selector, context, rootjQuery) {
      var match, elem;

      // HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) { return this; } // Handle HTML strings if (typeof selector === ‘string‘) { if ( selector.charAt(0) === ‘<‘ && selector.charAt(selector.length - 1) === ‘>‘ && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check match = [null, selector, null]; } else { match = rquickExpr.exec(selector); }

由這段代碼可知,jQuery.fn就是jQuery.prototype,現在要把jQuery的原型重寫,重寫一定會破壞constructor指向jQuery的這個構造函數,所以要手動添加;小寫的jquery是版本號

var jq = new Jquery()
console.log(jq.jquery) // 2.0.3

接下來是重點的init,沒錯就是那個不像構造函數的init

init: function(selector, context, rootjQuery) {
      var match, elem;

      // HANDLE: $(""), $(null), $(undefined), $(false)
      if (!selector) {
        return this;
      }

selector參數是選擇器字符串,其他兩個參數暫且不論,然後定義了match,elem;緊接著來了一個if語句,if(!selector)的意思就是selector為“”,null,undefined,false對應的情況註釋給我們了HANDLE: $(""), $(null), $(undefined), $(false) 處理四種獲取不到的情況,jQuery裏面直接去return this;不但終止了下列代碼的執行,還返回了this,這個this就是jQuery.prototype

// Handle HTML strings
      if (typeof selector === ‘string‘) {
        if (
          selector.charAt(0) === ‘<‘ &&                     /*   chatAt(下標)截取對應下標字符的意思
          selector.charAt(selector.length - 1) === ‘>‘ &&    *   這3句判斷了selector字符串是不是長<a>或<aaa>的總之要有一個尖括號,而且尖括號裏面必須有字符
          selector.length >= 3                               */  這句話並不能保證像<1>這種的
        ) {
          // Assume that strings that start and end with <> are HTML and skip the regex check
          match = [null, selector, null];
        } else {
          match = rquickExpr.exec(selector);
        }

這一段是如果$()括號裏面不是上述四種的情況,那麽就是一個有值的字符串。再進入一個if...else if語句(這裏截取的是if裏面嵌套的if else語句),如果selector是一個字符串類型,那麽就可以再判斷他是不是一個標簽類似於‘<aaa>‘,如果類似這種就把[null,selector,null]這樣一個數組賦值給前面定義的match,否則,像‘a<aa>‘或‘<br />r‘這種不符合以尖括號開頭和結尾的字符串,match就會等於rquickExpr.exec(selector);

那麽這是什麽意思呢?正則的exec()方法返回的是一個數組,那麽這個數組長什麽樣呢?上面已經定了rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,這就涉及到正則,簡單的說下:

學習源碼第三天(短暫的堅持)