jQuery的“$”实际上是一个函数。

var $ = fucntion jQuery(){ 
    return new jQuery.fn.init(selector);
};

jQuery.prototype = { 
    init: function(){},
    // ...jQuery的其他API
};

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

$(selector);

我们可以看到,“$”实际上就是调用了jQuery原型链上的构造函数,又因为这个构造函数的原型实际上就是jQuery的原型,所以就相当于直接返回了jQuery的原型上的方法。

所以jQuery的巧妙之处就在于,它在原型方法jQuery.fn.init上,返回原构造函数的原型方法jQuery.prototype,也就是jQuery.fn.init.prototype =jQuery.fn。这样做的好处一个是可以获取到jQuery绑定的原型方法,另一个是不需要new,因为我们new init时,init的原型就可以拿到jQuery的原型了。

更多推荐

jQuery中$的实现原理