您的位置:首页 > Web前端 > JQuery

jquery源码研究(原型继承)

2012-04-27 15:35 225 查看
观看者:javascript,jquery爱好者。需要一定的继承基础,如果没有可以看我的javascript深入了解(继承)

目标:了解jquery原型继承,实现jquery选择器的基础 $("id"),$("input") ...

实现方式:代码及相关文字解释。从最简单方式逐步推进。

首先用一个实现一个简单的实现:$("id") 返回一个jquery对象有一个方法tagName();于是我想到这样的:

$ = window.JQuery = function(id){
return new JQuery(id);
}
写到这里我实在写不下去了应为我想返回一个jquery对象,但是当我new调用的自身的构造函数,直接死循环。

那么我们可不可以new出一个另外的对象返回呢?

$ = window.JQuery = function(id){
return new JQuerylite(id);
}
JQuerylite = function(id){
this.dom = document.getElementById("dv");
this.tagName = function(){
alert(this.dom.tagName);
}
}
$("dv").tagName();
这样是可以实现的,但是不够完美,通过了两个无关的构造函数,实在浪费。我们可以换种思路,我们可以将JQuerylite修改成一个jquery的内部函数, 我们知道其实函数也是构造方法,这样一来我们的对象不仅指的是juqery对象,同时我们还有jquery原生的方法。一举两得下面是我们修改后的例子。

$ = window.JQuery = function(id){
return new JQuery.prototype.init(id);
}
JQuery.prototype = {
init:function(id){
this.dom = document.getElementById("dv");
this.tagName = function(){
alert(this.dom.tagName.toLowerCase());
};
this.version = '1.71';
},
version:'1.7',
name:'JQuery'
}
alert($("dv").version);//1.71
alert($("dv").name);//undefined
$("dv").tagName();//div
alert($("dv").name);//undefined,这个课不是我们想要的,我们需要的是JQuery里面的name值,为什么没有呢?

我前面的javascript深入了解(面向对象)里面也讲过,这里我再回顾一遍吧,当我们new 出来的JQuery.prototype.init(id),其实是调用的是JQuery.prototype.init的构造方法,如此一来我们共享的原型应该是JQuery.prototype.init.prototype = {},所以我们这里调用不到了,不过还有个方法是想法子将JQuery的prototype赋值给JQuery.prototype.init.prototype就行了。下面看例子:

$ = window.JQuery = function(id){
return new JQuery.prototype.init(id);
}
JQuery.prototype = {
init:function(id){
this.dom = document.getElementById("dv");
this.tagName = function(){
alert(this.dom.tagName.toLowerCase());
};
this.version = '1.71';
},
version:'1.7',
name:'JQuery'
}
JQuery.prototype.init.prototype = JQuery.prototype;
alert($("dv").version);//1.71
alert($("dv").name);//undefined
$("dv").tagName();//div
到此我们已经把基本的构造得到了,下一步我们来写个选择器的简单例子,用来练习一下吧:

实现以$(selector,context).size() 得到dom个数,selector 可以是id或者是标签名,context 是范围。

(function(){
$ = window.JQuery = function(selector,context){
return new JQuery.prototype.init(selector,context);
}
JQuery.prototype = {
init:function(selector,context){
var selector = selector ? selector : document;
var context = context ? context : document;
var dom;
if(dom = context.getElementById(selector)){
this[0] = dom;
this.length = 1;
}else{
dom = context.getElementsByTagName(selector);
for(var i=0; i<dom.length; i++){
this[i] = dom[i];
}
this.length = dom.length;
}
},
version:'1.7',
size:function(){
return this.length;
}
}
JQuery.prototype.init.prototype = JQuery.prototype;
})();
alert($("div").size());//3
alert($("dv").size());//1
就是想讲一下jquery一个机制,jquery的选择器当然比这个要强大的更多。为什么要用私有作用域((function(){})();)包起来呢?其实是为了怕会影响其他的外部函数和变量。想了解匿名函数的原理还需要看我原来写的文章javascript深入了解(私有作用域)。

新博客地址:l-zhi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: