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:
- (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 = Window.jquery,
- Map over the $ in case of overwrite
- _$ = window.$,
- ......
- IndexOf = Array.prototype.indexOf;
- Expose JQuery to the global object
- Window.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 the jquery, and this code represents To export the previously defined jquery 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:
- 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:
- 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 ());
- });
- Results nameerrortip Display, "Please enter king!" Popup
- Html:<input value= "King" id= "name"/><div id= "nameerrortip" > Input Error! </div>
- Results Nameerrortip Hidden, popup "Yes, input as king! "
Here "(Value=nameinput.val (), value==" King ")" () "in" () "the expression inside as a whole operation, and the inside expression is composed of", "composed of multiple expression groups, So it executes the multiple expressions once and returns 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:
- E.circular | | (F.onbeforeseek (function (A, b) {
- SetTimeout (function () {
- 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 | | 50);
- 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.
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:
- 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:
- Html:<input value= "King" id= "MyName"/>
- Result: Popup "No name input box found or input box 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
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.
Learn to read jquery and other JS plugin source code