但由于工作的原因,很久不曾做过网站项目了,也没有时间去好好研究Jquery的源码,这个疑问也一直没有得到解决了, 今天,空闲之余,打开Jquery的源码看看,才明天它实现的原理,原来在加入jquery的js这个文件时,实际上是执行了一个函数,在这个函数里己经初始化了$和JQuery变量, 实现这个功能源码如下(代码已删减和更改,并不影响说明实现原理): 复制代码 代码如下: (function() { var // Will speed up references to window, and allows munging its name. window = this, // Will speed up references to undefined, and allows munging its name. undefined, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery = window.jQuery = window.$ = function(selector, context) { // The jQuery object is actually just the init constructor "enhanced" return new jQuery.fn.init(selector, context); }, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<(.|s)+>)[^>]*$|^#([w-]+)$/, // Is it a simple selector isSimple = /^.[^:#[.,]*$/; jQuery.fn = jQuery.prototype = { init: function(selector, context) { // Make sure that a selection was provided // Make sure that a selection was provided selector = selector || document; this[0] = selector; this.length = 1; this.context = selector; return this; }, show:function() { alert("this.show"); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.3.2" }; jQuery.fn.init.prototype = jQuery.fn; })(); function test(src){ alert($(src)); $(src).show();
从代码里我们可以看到有这样一个函数执行了(funtion(){})();
var window = this; _jQuery = window.jQuery; _$ = window.$;