-
jQuery框架使用方式的特點
-
不使用new關鍵字直接調用jQuery函數返回jQuery對象
-
jQuery對象中包含DOM元素
-
該對象可鏈式調用內置屬性和方法(API)
-
- jQuery用法示例
// html
<div></div>
// js
$('div')
// 返回結果
jQuery.fn.init [div, prevObject: jQuery.fn.init(1)]
0: div
length: 1
prevObject: jQuery.fn.init [document]
__proto__: Object(0)
-
jQuery的整體架構分析
-
全面使用( 面向對象編程 && 原型鏈編程 )
-
實例方法都掛載到原型上
-
工具方法都掛載到函數上
// 利用閉包封裝jQuery防止污染全局變量 (function(global, factory){ factory(global); }(typeof window !== 'undefined' ? window : this, function(window){ // 掛載到window window.jQuery = window.$ = jQuery; // 調用該方法返回jq對象 function jQuery(selector) { return new jQuery.prototype.init(selector); } jQuery.prototype = { // init爲構造函數構造jq對象 init: function(selector) { ... }, // 內置屬性和API舉例 css: function() { console.log('css'); // 實現鏈式調用 return this; }, html: function() { console.log('html'); // 實現鏈式調用 return this; } } // 使jQuery.prototype可掛載一些內置屬性方法,jq對象可順着原型鏈訪問 jQuery.prototype.init.prototype = jQuery.prototype }));
-