博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
浅析jQuery基础框架
阅读量:4451 次
发布时间:2019-06-07

本文共 1945 字,大约阅读时间需要 6 分钟。

一、原型模式结构

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全局变量接口。

转载请注明转自

转载于:https://www.cnblogs.com/yangjunhua/archive/2012/12/27/2835989.html

你可能感兴趣的文章
类的继承、菱形继承、派生、多态
查看>>
mysql约束
查看>>
javascript鼠标及键盘事件总结及案例
查看>>
mysql表之间的关系及级联操作
查看>>
mac 搭建virtualenv的那些坑
查看>>
多路复用IO模型
查看>>
并发、串行、并行及多道技术原理
查看>>
hashlib、pickle、hmac、logging模块使用
查看>>
javascript常用知识点总结
查看>>
2019秋招复习笔记--数据库基本操作
查看>>
2019秋招复习笔试--手写代码
查看>>
2019秋招复习笔记--智力题
查看>>
MySQL学习笔记
查看>>
2019秋招面试复习 项目重点提问
查看>>
面试题
查看>>
DS博客作业08-课程总结
查看>>
利用Python爬虫刷店铺微博等访问量最简单有效教程
查看>>
浅谈软件测试与墨菲定律
查看>>
文件安全复制之 FastCopy
查看>>
强烈推荐美文之《从此刻起,我要》
查看>>