读jq之一(jq对象的构成)

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

以下是jquery 1.3.2 代码片段

...
jQuery = window.jQuery = window.$ = function( selector, context ) {
	return new jQuery.fn.init( selector, context );
};
jQuery.fn=jQuery.prototype={
	init:function(){...},
        ...
}
jQuery.fn.init.prototype = jQuery.fn;
...

 

初看上去像是在用原型方式 定义一个类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来写一个

function $(selector){
	return new $.prototype.init(selector);
}
$.prototype={
	init:function(selector){
		if(selector.nodeType==1){
			this[0] = selector;
		}else{
			this[0]=document.getElementById(selector);
		}
                this.length=1;
	},
	attr:function(name,value){
		this[0].setAttribute(name,value);
		return this;//链式调用
	},
	hide:function(){
		var self=this;
		setTimeout(function(){
			self[0].style.display="none";
		},3000);
		return this;//链式调用
	}
}
$.prototype.init.prototype=$.prototype;

 

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

var obj = $();
console.dir(obj);

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

length:0;

init:function

attr:function

hide:function

 

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

 

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

$("content").attr("bgcolor","red").hide();

 

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

 

总结下:

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

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

jQuery = window.jQuery = window.$ = function( selector, context ) {
	return new jQuery.fn.init( selector, context );
},

 

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({...})方式扩展的属性或方法。(见下一篇)