您的位置:首页 > Web前端 > JQuery

浅析jQuery基础框架

2013-01-23 16:44 183 查看
转自:/article/5937655.html


博客园浅析jQuery基础框架



一、原型模式结构

1 // 定义一个jQuery构造函数
2 var jQuery = function() {
3
4 };
5
6 // 扩展jQuery原型
7 jQuery.prototype = {
8
9 };


上面是一个原型模式结构,一个jQuery构造函数和jQuery实例化对象的的原型对象,我们一般是这样使用的:

1 var jq = new jQuery(); //变量jq通过new关键字实例化jQuery构造函数后就可以使用原型对象中的方法,但是jQuery并不是这么使用的




二、返回选择器实例

1 var jQuery = function() {
2
3     // 返回选择器实例
4     return new jQuery.prototype.init();
5 };
6 jQuery.prototype = {
7
8     // 选择器构造函数
9     init: function() {
10
11     }
12 };


虽然jQuery不是通过new关键字实例化对象,但是执行jQuery函数仍然得到的是一个通过new关键字实例化init选择器的对象,如:

1 var navCollections = jQuery('.nav');  //变量navCollections保存的是class名为nav的DOM对象集合.




三、访问原型方法

1 var jQuery = function() {
2
3     // 返回选择器实例
4     return new jQuery.prototype.init();
5 };
6 jQuery.prototype = {
7
8     // 选择器构造函数
9     init: function() {
10
11     },
12
13     // 原型方法
14     toArray: function() {
15
16     },
17     get: function() {
18
19     }
20 };
21
22 // 共享原型
23 jQuery.prototype.init.prototype = jQuery.prototype;


我们一般习惯称jQuery函数中返回的选择器实例对象为jQuery对象,如我们可以这样使用:

1 jQuery('.nav').toArray(); // 将结果集转换为数组


为什么可以使用toArray方法呢? 即如何让jQuery对象访问jQuery.prototype对象中的方法?只需将实例化选择器对象的原型对象共享jQuery.prototype对象,上面体现代码为:

1 jQuery.prototype.init.prototype = jQuery.prototype; // 共享原型




四、自执行匿名函数

1 (function(window, undefined) {
2
3     var jQuery = function() {
4
5         // 返回选择器实例
6         return new jQuery.prototype.init();
7     };
8     jQuery.prototype = {
9
10         // 选择器构造函数
11         init: function() {
12
13         },
14
15         //原型方法
16         toArray: function() {
17
18         },
19         get: function() {
20
21         }
22     };
23     jQuery.prototype.init.prototype = jQuery.prototype;
24
25     // 局部变量和函数在匿名函数执行完后撤销
26     var a, b, c;
27     function fn() {
28
29     }
30
31     // 使jQuery成为全局变量
32     window.jQuery = window.$ = jQuery;
33
34 })(window);


自执行匿名函数中声明的局部变量和函数在匿名函数执行完毕后撤销,释放内存,对外只保留jQuery全局变量接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: