现在的位置: 首页 > 综合 > 正文

读jquery之一(jquery对象的组成)

2012年05月29日 ⁄ 综合 ⁄ 共 2398字 ⁄ 字号 评论关闭

转自:http://snandy.iteye.com/blog/547429

 

以下是jquery 1.3.2 代码片段

Js代码  
  1. ...   
  2. jQuery = window.jQuery = window.$ = function( selector, context ) {   
  3.     return new jQuery.fn.init( selector, context );   
  4. };   
  5. jQuery.fn=jQuery.prototype={   
  6.     init:function(){...},   
  7.         ...   
  8. }   
  9. jQuery.fn.init.prototype = jQuery.fn;   
  10. ...  

 

 

初看上去像是在用原型方式 定义一个类jQuery($),但实际我们使用时是函数调用$("#id"),却不是new $("#id")。

function jQuery中new了一个function init的实例,然后返回。见具名函数的调用方式(3) 。jquery写的实在诡异,它把init又挂在了function jQuery的prototype上,阅读起来有些绕人。

 

jQuery.fn.init.prototype = jQuery.fn; 是关键的一句。该句把function jQuery的原型赋值给了function init的原型。当调用$("#id")时返回的对象组成包括两个部分。

1,由function init中this带的(如length,context);

2,由function jQuery的prototype带的(如size,each,attr等方法);

 

模仿jQuery来写一个

 

Js代码  
  1. function $(selector){   
  2.     return new $.prototype.init(selector);   
  3. }   
  4. $.prototype={   
  5.     init:function(selector){   
  6.         if(selector.nodeType==1){   
  7.             this[0] = selector;   
  8.         }else{   
  9.             this[0]=document.getElementById(selector);   
  10.         }   
  11.                 this.length=1;   
  12.     },   
  13.     attr:function(name,value){   
  14.         this[0].setAttribute(name,value);   
  15.         return this;//链式调用   
  16.     },   
  17.     hide:function(){   
  18.         var self=this;   
  19.         setTimeout(function(){   
  20.             self[0].style.display="none";   
  21.         },3000);   
  22.         return this;//链式调用   
  23.     }   
  24. }   
  25. $.prototype.init.prototype=$.prototype;  

 

简单起见,这里$只传html element或元素id,this上挂了length属性,赋值为1。当我们如下调用时

Js代码  
  1. var obj = $();   
  2. console.dir(obj);  

这行代码实际没有什么意义,只是为了测试调用后obj的组成。firebug控制台输出如下:

length:0;

init:function

attr:function

hide:function

 

即obj对象是由function init中this及function $.prototype组成的。

 

测试下$.prototype上的方法(假设页面body添加了id=content):

 

Js代码  
  1. $("content").attr("bgcolor","red").hide();  

先调用attr添加了id=content属性,稍候就隐藏了。

 

总结下:

jquery对象指的是jQuery.prototype.init的实例,简单的说就是new jQuery.prototype.init。

这里jQuery.prototype.init的类型是function,可以看成是一个类。源码中如下:

 

Js代码  
  1. jQuery = window.jQuery = window.$ = function( selector, context ) {   
  2.     return new jQuery.fn.init( selector, context );   
  3. },  

 

jQuery对象由以下部分组成:

1,挂在jQuery.prototype.init中的this上的属性或方法。

2,挂在jQuery.prototype.init.prototype上的属性或方法。

3,因为把jQuery.prototype赋值给了jQuery.prototype.init.prototype,所以挂在jQuery.prototype上的属性和方法也jQuery对象的一部分。

4,通过jQuery.fn.extend({...})方式扩展的属性或方法。(见下一篇)

 

 

抱歉!评论已关闭.