至今电脑里还存放着当时的api文档,发个图感叹下
在这段时间内,我的入门老师是墨墨,其实至今他仍然是我敬仰的同事之一。他的编程造诣很高,相信早已突破了编程语言的限制。在大家都在使用prototype.js的时候,在jquery尚未在国内流行的时候,他就已经把jquery引入到项目中了。
言归正传吧,目前的jquery版本已经到了1.6.1。从当时的2000行左右膨胀到了9000行。相信不久就会突破1w行。对于一些简单网页来说引入一个jquery已经不再那么轻量了。这里的研读的是1.6.1这个版本,我会边读边写,最后会写出一个1000行左右的“迷你jquery”。
以下是jquery 1.6.1 代码片段
复制代码 代码如下:
var jquery = function( selector, context ) {
// the jquery object is actually just the init constructor 'enhanced'
return new jquery.fn.init( selector, context, rootjquery );
},
...
class2type = {};
jquery.fn = jquery.prototype = {
constructor: jquery,
init: function(selector, context, rootjquery){
}
}
// give the init function the jquery prototype for later instantiation
jquery.fn.init.prototype = jquery.fn;
初看上去像是在用 原型方式 在写一个类jquery(别名$),但实际我们使用时是函数调用$(#id),却不是new $(#id)。
标识符 jquery是一个function,其内new了一个function init的实例,然后返回。至此我们知道其真正的构造器是jquery.fn.init。jquery写的实在诡异,它把init又挂在了jquery的prototype上,阅读起来有些绕人。jquery.fn.init.prototype = jquery.fn; 是关键的一句。该句把function jquery的原型赋值给了function init的原型。当调用$(#id)时返回的对象组成包括两个部分。
1,由function init中this带的(如this.context);
2,由function jquery的prototype带的(如this.size/this.toarray);
模仿jquery写一个
复制代码 代码如下:
// zchain-0.1.js
function $(selector){
return new $.prototype.init(selector);
}
$.prototype={
init:function(selector){
if(selector === undefined){
this.length = 0;
return this;
}
if(selector.nodetype==1){
this[0] = selector;
}else{
this[0]=document.getelementbyid(selector);
}
this.length=1;
},
css:function(name,value){
this[0].style[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(后续会增强,但不实现全部css selector),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上的方法,我只添加了css和hide方法,这两个方法的实现也是极其简陋的。
复制代码 代码如下:
3 seconds later i will hide.
先调用css设置了字体颜色为红色,3秒后隐藏了。
总结下:
jquery对象指的是jquery.prototype.init的实例,简单的说就是new jquery.prototype.init。这里jquery.prototype.init的类型是function,可以看成是一个类。
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({...})方式扩展的属性或方法(后续提到)。
/201106/yuanma/zchain.rar