The jquery source of reading notes

Source: Internet
Author: User

Many people think that jquery, ext and other open source JS source code is very obscure, read not understand, encountered problems need to debug also very laborious. In fact, I personally feel that there are several reasons for the main:

1, some JS not commonly used syntax, operators are not familiar with

2, a function is nested in some internal function, so that the entire code hierarchy is not as clear as Java code.

3, JS allowed variables first use after the definition, will cause us to look at the code when suddenly a variable, function, but can not find where is defined.

So let's share my experience and clear your obstacles today.

One, some obscure operators:

1, (function () {}) ();

Almost all open source JS code begins with this (function (...) {......}) (......);

Here is a partial source of jquery:

JS Code
  1. (function(window, undefined) {
  2. var jQuery = function(selector, context) {
  3. //The JQuery object is actually just the Init constructor ' enhanced '
  4. return new jQuery.fn.init (selector, context);
  5. },
  6. //Map over jQuery in case of overwrite
  7. _jquery = window.jquery,
  8. //Map over the overwrite
  9. _$ = window.$,
  10. ...
  11. indexOf = Array.prototype.indexOf;
  12. //Expose JQuery to the Global object
  13. window.jquery = window.$ = JQuery;
  14. }) (window);
(Function (window, undefined) {var jQuery = function (selector, context) {//The JQuery object is actually just the Init Constructor ' enhanced ' return new JQuery.fn.init (selector, context);},//Map over JQuery in case of overwrite_jquery = W indow.jquery,//Map over the $ in case of overwrite_$ = window.$,...... indexOf = array.prototype.indexof;//Expose jQuery to T He global objectwindow.jquery = window.$ = JQuery;}) (window);

So what does this operator (function () {}) () mean?

A function is defined in (function () {}) followed by () that immediately executes the function.

We see that the jquery source code first () is defined as an anonymous function (window, undefined) {}; Then at the end there is a (window) that executes the anonymous function and passes in the parameter window.

In anonymous function (window, undefined) {}, a local variable jquery is defined, and then at the end we see a sentence window.jquery = window.$ = jquery at the end of jquery; This code means that the previously defined jquery is exported to the Window object. This is why we can use the $, jquery object directly anywhere in the code, because here the $, jquery object is already attached to the window, and window.$, Window.jquery and the direct use of $, jquery is no different.

(Note that this window object is an incoming parameter window, not a browser window Object!!) A formal parameter, an argument. We can name the parameter window as a different character when defining the function. So we see that this anonymous function in Jquery.min.js becomes (function (e,b) {}) (window);)

Typically (function () {}) () is used to encapsulate the export of some private members or public members.

2. Confusing ","

We know that "," is typically used to define multiple variables at once, define multiple parameters, and so on. Like the jquery source above, after the Var jquery, use "," once defined a number of variables.

But, like the following code, you might not necessarily be able to read it:

JS Code
    1. //html:<input type= "hidden" value= "King" id= " namehide"/>
    2. jQuery (document). Ready (function() {
    3. var showname=function() {
    4. var value,nameinput=$ ("#nameHide");
    5. return nameinput.show (), Value=nameinput.val ();
    6. };
    7. alert (ShowName ());
    8. });
    9. //Result: Pop up king
Html:<input type= "hidden" value= "King" id= "Namehide"/>jquery (document). Ready (function () {var showname= function () {var value,nameinput=$ ("#nameHide"), return Nameinput.show (), Value=nameinput.val ();}; Alert (ShowName ());}); /result: Pop up King

The function of the "," operator in "Nameinput.show (), Value=nameinput.val ()" Here is to return the value of the expression on the right-hand side. So, if there are multiple expressions after return, and the expression is separated by ",", the entire return expression returns the value of the expression to the right of the last ",".

"," is often used in open source code in return expressions, and in conjunction with the "()" operator we're going to talk about below.

3, "()" in the broad sense of the code packaging

When we encounter complex logical expressions, we usually wrap the expression "()" in a way that requires an operation: (a| | b) && (c| | D

In fact, we can understand that the "()" operator wraps an expression together as a whole and then returns the value of the whole.

then the function () in the left-hand definition (function () {}) () is also the role, wrapping the function and returning the function. The method we invoke is typically a (), so (function () {}) is used to return the function object, and () () to the right of (function () {}) () means that the function is called.

Let's look at other uses:

JS Code
  1. //html:<input value= "Kings" id= "name"/><div id= "nameerrortip" > Input Error! </div>
  2. jQuery (document). Ready (function() {
  3. var namevalidate=function() {
  4. var value,nameinput=$ ("#name"), nameerrortip=$ ("#nameErrorTip" );
  5. return (Value=nameinput.val (), value=="King")? ( Nameerrortip.hide (),"Yes, input is king! "):(nameerrortip.show ()," Please enter king! " );
  6. };
  7. alert (Namevalidate ());
  8. });
  9. //Results Nameerrortip display, popup "Please enter king!"
  10. //html:<input value= "King" id= "name"/><div id= "nameerrortip" > Input Error! </div>
  11. //Results Nameerrortip hidden, popup "Yes, input is king! "
Html:<input value= "Kings" id= "name"/><div id= "nameerrortip" > Input Error! </div>jquery (document). Ready (function () {var namevalidate=function () {var value,nameinput=$ ("#name"), nameerrortip=$ ("#nameErrorTip"); Return (Value=nameinput.val (), value== "King")? (Nameerrortip.hide (), "Yes, input is king! "):(nameerrortip.show ()," Please enter king! "); Alert (Namevalidate ());}); /result nameerrortip display, popup "Please enter king!" Html:<input value= "King" id= "name"/><div id= "nameerrortip" > Input Error! </div>//results Nameerrortip Hidden, popup "Yes, input is king! "

Here "(Value=nameinput.val (), value==" King ")" () "in" () "the expression inside as a whole operation, and the expression inside is composed of", "composed of multiple expression groups, so the execution of the time will be These multiple expressions are executed once and return the value of the last expression!

therefore (Value=nameinput.val (), value== "King"), the value of the first operation, and then determine whether it is "king". If it is king, it executes (Nameerrortip.hide (), "Yes, enter as king! ")。 This expression first hides the Nameerrortip, and then returns a "Yes, the input is king! "String as the value of the entire return.

4, | |, &&, if () logic makes people dizzy

| |, && both sides participate in the operation of the logical expression, if () is also. But what we see in many open-source code is that the expressions for the | |, && participate in the operation don't seem to be logical expressions ...

Here is an excerpt from a section of the source code in Jquery.tool:

JS Code
  1. E.circular | | (F.onbeforeseek(function(A, b) {
  2. setTimeout (function() {
  3. a.isdefaultprevented ()
  4. || (N.toggleclass (E.disabledclass,
  5. b <= 0), O.toggleclass (
  6. E.disabledclass, b >= F
  7. . GetSize ()
  8. -1))
  9. }, 1)
  10. }), E.initialindex | | N.addclass (E.disabledclass)), F.getsize () < 2
  11. && n.add (o). addclass (E.disabledclass), E.mousewheel
  12. && a.fn.mousewheel && b.mousewheel (function(A, b) {
  13. if (e.mousewheel) {
  14. F.move (b < 0? 1:-1, E.wheelspeed | |);
  15. return ! 1
  16. }
  17. });
E.circular | | (F.onbeforeseek (function (A, b) {setTimeout () {a.isdefaultprevented () | | | (N.toggleclass (e.disabledclass,b <= 0), O.toggleclass (E.disabledclass, b >= f.getsize ()-1)}, 1)}), E.initialindex | | N.addclass (E.disabledclass)), F.getsize () < 2&& n.add (o). addclass (E.disabledclass), e.mousewheel&  & A.fn.mousewheel && B.mousewheel (function (A, b) {if (E.mousewheel) {F.move (b < 0? 1:-1, E.wheelspeed | | Return 1}});

There are many places | |, &&. But the expression with the operation is the return value of the call to a function.

In fact, the logical expression in JS is based on the truth, false values to be divided. True is the truth, 1 is the truth, an object is the truth; false is a false value; "", and 0 is a false value.

in js &&, | | Not all are used to determine the logical value of an expression is true, false, more is used in accordance with the truth or false values to perform the corresponding operation!

we know, | | Operation, the value of the expression on the left is evaluated first, if true, then the expression is true, while the right expression is true, false value is not important, because the right expression will no longer participate in the operation. If the left is a false value, the right-hand expression continues to be evaluated.

&& Then the left-hand expression, both sides of the expression, one for the false value, the entire expression is a false value.

The key here is this truth or false value of the operation process, we can use the ",", "()" described above to string together a set of expressions to execute. In other words, this expression may be very long and I can even define a function inside. These expressions have some additional operations that can be performed during execution. For example, we want this expression to be true when we do what, what to do when the false value, the operation with "()", "," string up as a whole operation.

Then there is the complex code above.

In addition, note: The following notation is equivalent:

JS Code
    1. if(a) {
    2. b
    3. }
    4. //equivalent to
    5. a&& (b)
    6. //b can be a function call expression, or multiple statements with "," string up
if (a) {b}//is equivalent to a&& (b)//b can be a function call expression, or multiple statements with "," string up

Let's take a look at an example. is an upgraded version of the above example. We add a nameinput whether the existence of the judgment:

JS Code
    1. jQuery (document). Ready ( function () {
    2. /span> var namevalidate= function () {
    3. var value,nameinput=$ ( #name ), nameerrortip=$ ( #nameErrorTip ), MSG;
    4. msg= (Value=nameinput.val (), value== "King" )? ( Nameerrortip.hide (), "Yes, the input is king! ):(nameerrortip.show (), "Please enter king!" );
    5. return (Nameinput.length&&nameinput.val () && NAMEERRORTIP.LENGTH&&MSG) | | "The name input box is not found or the input box has no value!" " ;
    6. };
    7. alert (namevalidate ());
    8. });
JQuery (document). Ready (function () {var namevalidate=function () {var value,nameinput=$ ("#name"), nameerrortip=$ ("# Nameerrortip "), msg;msg= (Value=nameinput.val (), value==" King ")? (Nameerrortip.hide (), "Yes, input is king! "):(nameerrortip.show ()," Please enter king! "); Return (Nameinput.length&&nameinput.val () &&nameerrortip.length&&msg) | | " The name input box is not found or the input box has no value! ";}; Alert (Namevalidate ());});

Test:

JS Code
    1. //html:<input value= "King" id= "MyName"/>
    2. //Result: Popup "No name input box found or input box has no value!" "
    3. //<input value= "King" id= "name"/><div id= "nameerrortip" > Input Error! </div>
    4. //Result: Popup "Yes, input is king! ", Nameerrortip was hidden
Html:<input value= "King" id= "MyName"/>//Result: Popup "The name input box is not found or the input box has no value!" "//<input value=" King "id=" name "/><div id=" nameerrortip "> Input Error! </div>//Result: Popup "Yes, input is king! ", Nameerrortip was hidden

The return indicates that the Nameinput.length&&nameinput.val () &&NAMEERRORTIP.LENGTH&&MSG will first operate The value of the nameinput.length, if length is 0, the expression is false, and if 1 is the true value. The Val () operation is also true if the Val () result is "" and the expression is also a false value. a && operation between several expressions means that the values of several expressions are evaluated sequentially, and the value of the last expression is returned if none is true, because the entire expression and

"The name input box is not found or the input box has no value!" "

Between Expressions is | | Operation, so one of the preceding expressions is a false value returns | | The value of the expression on the right, that is, the entire "No Name input box found or the input box has no value!" String

Speaking of which, I have written an article about &&, | | The problem of true value and false values. Interested can go and have a look. http://my249645546.iteye.com/blog/1553202

After talking about these incomprehensible operators, you might think why this JavaScript is doing these obscure operators?

My understanding is that JavaScript usually runs on the client side, so transferring the JS code from the server to the client must be time-consuming. The above operators are all designed to reduce the amount of code. Plus using the compression tool to remove the space, replace the variable name, you can use the compression rate to achieve the best.

Again here, I also tell you, in fact, I am also very opposed to the use of this writing in practical applications, because it will create dyslexia for beginners. The purpose of this article is not to let everyone use it later, but to tell you can use it, in some open source code encountered can understand. Do not intentionally write obscure code to show off.

Finally, in order to help us find the definition of variables faster, clear the overall structure of the Code, we recommend an Eclipse JS plugin: spket, support jquery code hints Oh!

The jquery source of reading notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.