jQuery源碼 逐行解析之變量函數定義

變量定義

var  
 rootjQuery,
// rootjQuery = jQuery(document) 
readyList,
// 用於DOM加載,dom就是網頁一個一個的標籤在內存中表示成dom樹
core_strundefined = typeof undefined,
// typeof undefined == 'undefined' 等於字符串形式的"undefined"
    /** 咱們要明確,上面穿了undefined,
    這個undefined不是保留字也不是關鍵字,
    它只是window下的一個屬性,
    因此在某些狀況下這個undefined能夠被更改 **/

location = window.location,//網址信息
document = window.document,//document對象
docElem = document.documentElement,//html標籤
 // 利於壓縮 
_jQuery = window.jQuery, //=>參考下面解釋
_$ = window.$,
// 防衝突用,當不當心 給$賦值時,先用賦的值,若是沒有賦值,這兩個東西是undefined
class2type = {},
// 類型有關 $.type()
// class2type = {'[Object String]':'string','[Object Array]':'array'}
core_deletedIds = [],
// 緩存數據有關,如今不用了 改用面向對象以後

core_version = "2.0.3",
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim, //去掉空格
// 存儲了經常使用的數組方法和對象字面量方法,利於代碼壓縮
// Save a reference to some core methods
大多數是爲了便於維護壓縮用的,變量名有意義.

函數定義

jQuery = function (selector, context) {
  return new jQuery.fn.init(selector, context, rootjQuery);
},

入口函數 window.$=window.jQuery=jQueryjavascript

  1. 咱們要明確 這個就是咱們用的$().css() 對象方法,這個返回了一個對象,那麼fn是什麼

參看這一句css

//代碼70-96 
jQuery.fn = jQuery.prototype = {
   ......
};
fn就是JQ的原型,可是在JQ原型下的方法怎麼弄被JQ.fn.init函數使用呢?這個是返回了一個對象和JQ有什麼關係呢?
//普通構造函數及使用方法
function arry(){ //構造函數
....
}
//構造函數原型下面加些其它方法
arry.prototype.init=function(){ //init調用就執行
....
}
//
arry.prototype.push=function(){
....
}
//調用
var arr1 = new arry(); //拿構造函數new 出一個實例化對象
arr1.init(); //對象方法調用
arr1.push();
咱們來看看JQ裏面怎麼作的
jQuery = function (selector, context) {
    return new jQuery.fn.init(selector, context, rootjQuery);
  },
 jQuery.fn = jQuery.prototype = { ... };
 jQuery.fn.init.prototype = jQuery.fn;
  1. 在上面JQ原型賦給了fn,fn=JQ原型,
  2. JQ原型又給了 JQ原型下init函數下的原型, 而JQ原型自己就是一個對象,對象賦值對象就造成了引用

正則定義

// Used for matching numbers 匹配數字
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,

// 匹配單詞,之間不存在空格的元素,用空格分開
core_rnotwhite = /\S+/g,
// |以前匹配標籤 以後 匹配id
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,

// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,

 /**
 webkitMarginLeft 但在ie有問題,
 在ie轉換的話第一個字母不是小寫而是大寫MsMarginLeft
 **/
rmsPrefix = /^-ms-/,
// 轉換大小寫,-l ==> L , -2d ==> 2d
rdashAlpha = /-([\da-z])/gi,
防止xss注入:

image.png

咱們在頁面跳轉時,有些網站每每用id做爲跳轉,在早前的瀏覽器咱們能夠這麼寫
image.png
這麼寫不是跳轉頁面,而是建立div,在早前是這樣的,如今經過 rquickExpr 匹配 它只識別真正的id 而不是 帶尖括號的標籤

函數定義2

// 轉駝峯的回掉函數,就是駝峯寫法
fcamelCase = function (all, letter) {
  return letter.toUpperCase();
},
// dom加載成功觸發的
completed = function () {
  document.removeEventListener("DOMContentLoaded", completed, false);
  window.removeEventListener("load", completed, false);
  jQuery.ready();
};

未完待續....html

相關文章
相關標籤/搜索