In the flops I understood in the jquery (1) message, I saw a friend wrote "jquery intrusive too strong to die", I do not know whether because the author's article is not good, offended him, let the author "Die", or let jquery "to die." If for the author personally, this is not what, the most I will seal the pen, but if it is to say "jquery intrusive" and let jquery "to die", I would have said.
First of all, jquery is not only intrusive, but also very good encapsulation, it can be said very good. What's the solution?
1. We look at the entire code of jquery, completely encapsulated in an anonymous function, the structure of which is generally as follows:
(function() {
/*
此处为jQuery的逻辑代码
*/
})()
All of the jquery code is encapsulated in this anonymous function (how can I ask for a bike again?)! Why use anonymous functions? This is also to ensure that the encapsulation, in addition to this function, can not be invoked.
How does an anonymous function execute? In fact, here's a trick to put a JavaScript snippet into a bracket (), followed by a bracket (), so that the code snippet within the first bracket is executed immediately, which I usually call the "execute function immediately". In fact, the named function can also be executed immediately, as follows:
<script type="text/javascript">
(function() {
/*
此处为jQuery的逻辑代码
*/
})();
(function xieRan() {
alert("my name is xieran.");
})();
</script>
So if you run this code, he will immediately pop up an alert alert box. You can also give an immediate function pass parameter, as follows:
(function xieRan(形参A, 形参B) {
alert("my name is " + 形参A + " and I live in " + 形参B);
})("xieran", "qingdao");
How elegant it is to execute the function immediately, and recall that we used to perform a function-first defining the function, and then writing a line of code to step through it-was the original wording a little "clumsy", as follows:
function xieRan(userName) {
alert("my name is " + userName);
};
xieRan("xieran");
A named function can be step-by-step, but an anonymous function can be run only by a structure that executes immediately.
2. Let's see what jquery did to the top of window.
From the first point above, we know that the whole of jquery is a big anonymous function, and we typically load jquery into our page (which is actually loaded into the Window object) in the following way:
<script type="text/javascript" src="YOURPATH/jQuery.js"></script>