码迷,mamicode.com
首页 > Web开发 > 详细

jQuery对象的创建(一)

时间:2017-05-28 12:30:30      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:type   访问   return   选择   执行   his   span   init   入口   

在jQuery的常规用法中,执行“$()”返回的是一个jQuery对象,在源码中,它是这样定义的:

...
var jQuery = function() {
    return new jQuery.fn.init();
}
...
jQuery.fn = jQuery.prototype;

可以得出以下几个结论:

1、jQuery.fn.init()就是jQuery.prototype.init();
2、init()函数是一个构造函数,就是通过调用它创建的jQuery对象,它定义在jQuery()的原型中;

...
var init = jQuery.fn.init = function(){
    ...
    return this;
}
init.prototype = jQuery.fn;

可以得出以下几个结论:
1、init()构造函数最后返回了这个新对象的引用;
2、用jQuery()的原型覆盖了init()的原型;

 

现在的问题是,为什么jQuery会这么写呢?
再看一遍,我们的目的是创建一个jQuery类,它包含了一系列可调用的函数,实例化这个类得到jQuery对象,它可以这么写:

var jQuery = function(){
    ...
}
jQuery.prototype = function(){
    ...
}
var j = new jQuery();

显然,jQuery不是这样的,他使用了无new构造,就像下面这样:

var jQuery = function(){
    return new init();
}
jQuery.prototype = function(){
    ...
}
var init = function(){
    ...
    return this;
}
init.prototype = function(){
    ...
}

但是,如果这样写,jQuery函数就仅仅成为一个入口了,init函数才是真正的实现,因此jQuery将init()放在了jQuery.prototype()里面,即:

var jQuery = function(){
    return new jQuery.prototype.init();
}
jQuery.prototype = function(){
    ...
    init: function(){
        ...
        return this;
    }
}
init.prototype = function(){
    ...
}

此时,还有一个问题:新创建的对象无法访问jQuery.prototype()中的其他属性,解决方法是:将jQuery.prototype传递给jQuery.prototype.init.prototype

var jQuery = function(){
    return new jQuery.prototype.init();
}
jQuery.prototype = function(){
    ...
    init: function(){
        ...
        return this;
    }
}
jQuery.prototype.init.prototype = jQuery.prototype;

创建jQuery对象的整个流程如下:

“调用$()方法”->“调用jQuery.prototype.init()构造函数”->“根据选择器不同返回不同的jQuery对象”->“不同jQuery对象中相同的方法写在jQuery.prototype中”->“将jQuery.prototype传递给jQuery.prototype.init.prototype,这样新创建的对象才可以访问通用方法”

jQuery对象的创建(一)

标签:type   访问   return   选择   执行   his   span   init   入口   

原文地址:http://www.cnblogs.com/blog-cxj2017522/p/6915360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!