But due to work reasons, I haven’t done a website project for a long time, and I don’t have time to study the source code of Jquery. This question has not been solved. Today, in my spare time, I will open the source code of Jquery and take a look, and it will be implemented tomorrow. The principle is that when adding the js file of jquery, a function is actually executed, in which the $ and JQuery variables have been initialized. The source code to implement this function is as follows (the code has been deleted and changed, and it does not affect Explain the implementation principle):
(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();
From the code we can see that there is such a function executed ( funtion(){})();
var window = this;
_jQuery = window.jQuery;
_$ = window.$;
These lines of code should It is to declare jQuery and $ variables. As for why it can be used like this, I haven’t figured it out yet. I’ll wait for experts to solve it! !
But I think it doesn’t matter, because the most important thing is the following code:
jQuery = window.jQuery = window.$ = function(selector, context) {
return new jQuery.fn.init(selector, context);
};
It can be seen that creating a function like jQuery.fn.init returns to $. In this way, the $ instance can be used, but not yet. To access the methods in jQuery.fn, you need to add the following sentence:
jQuery.fn.init.prototype = jQuery.fn;
achieves these, and other functions in Jquery are It's easy to understand. It's nothing more than adding methods in prototype or extend.