jQuery源码分析(2) - 为什么不用new jQuery而是用$()

 

把以前看的jQuery源码的分析笔记搬到博客上,重温经典,也是为了方便查询。

 

var jQuery = function(selector, context){
    return new jQuery.fn.init(selector, context);
};
jQuery.fn = jQuery.prototype = {
    constructor: jQuery,
    init: function() {
        return this;
    }
};

jQuery.fn.init.prototype = jQuery.fn;

jQuery('p');
jQuery没有使用new来实例化jquery,而是直接调用其函数,要实现这样,要把jquery看成一个类,而且返回一个正确的实例,
实例还要能正确访问jquery类原型上的方法和属性,通过传递原型,使得init方法生成的实例的this最后仍然能指向jQuery.prototype,
所以仍然能调用jQuery类原型上的属性与方法。
 
posted @ 2019-09-11 11:25  贾各布  阅读(314)  评论(0编辑  收藏  举报