模拟JQuery的实现:
1、起源—原型继承
var $ = jQuery = function(){}
jQuery.fn = jQuery.prototype = {
jquery: "1.3.2", //原型属性
size: function() { //原型方法
return this.length;
}
}
2、生命—返回实例
①、第一步
var $ =jQuery = function(){
return new jQuery(); //返回类的实例
}
jQuery.fn = jQuery.prototype = {
jquery: "1.3.2",
size: function() {
return this.length;
}
}
②、第二步
var $ =jQuery = function(){
return jQuery.fn.init(); //调用原型方法init()
}
jQuery.fn = jQuery.prototype = {
init : function(){ //在初始化原型方法中返回实例的引用
return this;
},
jquery: "1.3.2",
size: function() {
return this.length;
}
}
3、学步—分隔作用域
①、第一步
var $ =jQuery = function(){
return jQuery.fn.init();
}
jQuery.fn = jQuery.prototype = {
init : function(){
this.length = 0;
this.test = function(){
return this.length;
}
return this;
},
jquery: "1.3.2",
length: 1,
size: function() {
return this.length;
}
}
测试结果:
alert( $().jquery ); //返回"1.3.2"
alert( $().test() ); //返回0
alert( $().size() ); //返回0
②、第二步
var $ =jQuery = function(){
return new jQuery.fn.init();
}
jQuery.fn = jQuery.prototype = {
init : function(){
this.length = 0;
this.test = function(){
return this.length;
}
return this;
},
jquery: "1.3.2",
length: 1,
size: function() {
return this.length;
}
}
测试结果:
alert( $().jquery ); //返回undefined
alert( $().test() ); //返回0
alert( $().size() ); //抛出异常
4、生长—跨域访问
var $ =jQuery = function(){
return new jQuery.fn.init();
}
jQuery.fn = jQuery.prototype = {
init : function(){
this.length = 0;
this.test = function(){
return this.length;
}
return this;
},
jquery: "1.3.2",
length: 1,
size: function() {
return this.length;
}
}
jQuery.fn.init.prototype = jQuery.fn; //使用jQuery的原型对象覆盖init的原型对象
测试结果:
alert( $().jquery ); //返回"1.3.2"
alert( $().test() ); //返回0
alert( $().size() ); //返回0
5、成熟—选择器
var $ =jQuery = function(selector, context ){ //定义类
return new jQuery.fn.init(selector, context ); //返回选择器的实例
}
jQuery.fn = jQuery.prototype = { //jQuery类的原型对象
init : function(selector, context){ //定义选择器构造器
selector = selector || document; //设置默认值为document
context = context || document; //设置默认值为document
if ( selector.nodeType ) { //如果选择符为节点对象
this[0] = selector; //把参数节点传递给实例对象的数组
this.length = 1; //并设置实例对象的length属性,定义包含元素个数
this.context = selector; //设置实例的属性,返回选择范围
return this; //返回当前实例
}
if ( typeof selector === "string" ) { //如果选择符是字符串
var e = context.getElementsByTagName(selector); //获取指定名称的元素
for(var i = 0;i<e.length;i++){ //遍历元素集合,并把所有元素填入到当前实例数组中
this[i] = e[i];
}
this.length = e.length; //设置实例的length属性,即定义包含元素的个数
this.context = context; //设置实例的属性,返回选择范围
return this; //返回当前实例
} else{
this.length = 0; //否则,设置实例的length属性值为0
this.context = context; //设置实例的属性,返回选择范围
return this; //返回当前实例
}
},
jquery: "1.3.2",
size: function() {
return this.length;
}
}
jQuery.fn.init.prototype = jQuery.fn;
本文逐步解析了如何从原型继承开始,逐步构建出类似JQuery的功能实现过程,包括返回实例、分隔作用域、跨域访问及选择器的实现。
772

被折叠的 条评论
为什么被折叠?



