看看jquery初始化时做的“好事”。。。

[html] <div class="post-meta'">test me</div> [/html] [javascript] var jQuery = $ = function(selector, context) { // jQuery 对象就是 init 函数的一个实例 return new jQuery.fn.init(selector, context); } jQuery.fn = jQuery.prototype = { init: function(selector, context) { //选择器名称 this.selector = selector; //选择上下文[说白了就是从那里开始选择,同理,如果不在这个上下文中,选择不到的。。。。] //一般默认不填写,直接就是document,只要有不会出现选择不到的情况 this.context = (context || window.document).querySelectorAll(selector);     return this; } } console.dir($('.post-meta',document.getElementById('main')) ); [/javascript] 当然除了这些”好事“jquery还做了一系列工作,但这是它的核心,如果没这一段jquery是不可能成立的。。。。。。 另外有张图片非常完美的诠释了jquery jQuery.fn = jQuery.prototype; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 由于 jQuery 对象就是 init 函数的一个实例,为了使这个对象更加强大。有了这句 jQuery.fn.init.prototype = jQuery.fn; 为什么要 jQuery.fn = jQuery.prototype,然后 jQuery.fn.init.prototype = jQuery.fn;??? 其实一般做法是这样的,var $ = new jQuery(); 但jquery的设计们为了省略掉每次都烦人的 new 操作符,所以饶了这么一个大弯儿,这样只要你加载了这个库, var jQuery = $ = function(selector, context) { // jQuery 对象就是 init 函数的一个实例 return new jQuery.fn.init(selector, context); } 这段话一执行,一个全局的jQuery就这么出生了,只要你jQuery()这样一调用,立即返回一个全新的jQuery对象,这就对象就是 return new jQuery.fn.init(selector, context),构造函数是 jQuery.fn.init(),有一点发现jQuery1.4.2已经不重视prototype.constructor这个构造器问题,完全不理会构造器。其实这样做有这样做的道理,jQuery里不管是 fn.fucntion功能还是jQuery.function功能,都是通过一个 jQuery.extend = jQuery.fn.extend 等同的扩展函数扩展而来的,没有什么继承特色,当然在jQuery里也不需要什么继承特色,javascript中的的继承本来就用的不多,这一点在 jQuery里特别体现出来了。所以在jQuery里扩展才是王道。jQuery就这样不断的扩展它的功能,也就是不断的给自己返回的对象添加插件,说到插件这个概念,插件是发生对象身上的,也就是有了对象object在object初始化后动态添加的功能都应该叫插件,模块就是另一个概念了,模块是在对象初始化之前写入类中的。初始化之后就有了模块的功能,所以它们唯一的区别是绑带对象的时间不同而已,模块是娘胎里带的,插件出生之后装上的假肢。。。。。。。 这样说的话,jQuery其实就是一个千手观音,而且它的手是一只一只加上的,而且如果你发现它的手不够用,你就可以造一个你觉得完美的手给它装上去。 注:代码用例只有在firefox里能用,因为querySelectorAll这些东西ie不支持。当然jhon resig已经帮你解决了这个问题。
posted @ 2010-08-17 10:27  7hihi  阅读(151)  评论(0编辑  收藏  举报