(function ($) {}) (jQuery) data records

Source: Internet
Author: User

For anonymous functions you should be familiar with it, then (function ($) {}) (JQuery) is more understandable. is to write an anonymous function that also understands the invocation of the jquery argument passed.

Equivalent to:

  

var function

This kind of writing often appears in the various jquery plug-ins, the key reason is: There are many jquery plug-ins, you can not guarantee that your definition and use of variable/function name is not used in other plugins, the best way is to make your own code has "encapsulation" Then local variables and local functions are a good solution, which is to write all the content into an anonymous function.

Also, because jquery-based plug-ins use jquery itself, they need to be imported into anonymous functions.

When it comes to the key points of jquery, it's not a matter of professional front-end engineers looking at this part of the focus.

The following content sources "

I saw this before I realized that the jquery source code was not so obscure.

"

Some obscure operators: (function () {}) ();

Almost all open source JS code starts with this(function(……){……})(……);

Here is a partial source of jquery:

(function(window, undefined) {varJQuery =function(Selector, context) {//The JQuery object is actually just the Init constructor ' enhanced '        return NewJQuery.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 objectWindow.jquery = window.$ =jQuery;}) (window);

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

(function(){})In the definition of one function , followed by the () expression immediately executes this function .

We see the Jquery source code () is defined in the first one is anonymous and function( window, undefined ) {}; then the end has a (window) , it means to perform this anonymous function , and passed parameters window .

In anonymity function( window, undefined ) {} , a local variable is defined, jQuery and then at the end we see a sentence at the end that indicates that the Jquery window.jQuery = window.$ = jQuery; previous definition was jQuery exported to the window object. This is why we can use the object directly anywhere in the code, $ jQuery because it has been put on, the $ jQuery object is attached to it, and window window.$ , window.jQuery with direct use $ , jQuery there is no difference.

(Note that this window object is an incoming parameter window , not a browser window Object!!) A formal parameter, an argument. We can function name parameters as other characters at the time of definition window . So we see that this anonymity in Jquery.min.js function becomes(function(E,B){})(window);)

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

Confusing ","

We know that it is , common to define multiple variables at once, define multiple parameters, and so on. As in the jquery source above var jQuery , it is used , once to define 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 nameInput.show(),value=nameInput.val() function in the , operator here is to return , the value of the right-hand expression. So, return if there are multiple expressions later, and the expressions are , separated, the entire return expression returns the value of the last , right-hand expression.

,It's often used in expressions in open source code return , and in conjunction with the operators we're going to talk about here () .

()Code wrapping in the broadest sense

When we encounter complex logical expressions, we usually wrap the expressions that need to be worked together with "()":(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.

So the definition on the left side of the above (function(){})() function的() is also the function, function wrap it up and return it function . The general purpose of our invocation method is a(); (function(){}) to return this function object, and then the (function(){})() representation on the right side () calls this function .

Let's look at other uses:

//html:<input value= "Kings" id= "name"/><div id= "nameerrortip" > Input Error! </div>JQuery (document). Ready (function() {    varNamevalidate=function(){        varvalue,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! "

In this case (value=nameInput.val(),value=="king") () , the expression inside is evaluated as a whole, and the expression in it is made up , of multiple expression groups, so the execution of the expression will be executed once, and return the value of the last expression!

Therefore (value=nameInput.val(),value=="king") , when executing, the value of the first operation, and value then determine whether it is "king" . If king it is, it will be executed (nameErrorTip.hide(),"对了,输入为king!") . This expression is then nameErrorTip hidden and returns a "对了,输入为king!" string as the entire return value.

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

||, the two && sides participate in the operation is a logical expression, if() also. But the expressions that we see in many open source code that || && participate in operations do not look like 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 here || , && . 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. Is the truth true 1 value; An object is also a truth; false it is false "" 0 ; it is a false value.

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

We know that, || when the operation, the value of the expression on the left, if it is true, then the first expression is true, while the right expression is true, false value is not important, because the right-hand expression is no longer involved in the operation. If the left is a false value, the right-hand expression continues to be evaluated.

&&Then the left-hand expression, the two-sided expression, and one false value, the entire expression is a false value.

The key here is that the truth or false value of the operation process, we can use the above described , , () a set of expressions string up execution. In other words, the expression may be very long and I can even define one 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 we do, what to do when the value is false, and to use these operations () , as a whole.

Then there is the complex code above.

Other than that:

if (a) {    B}

may be abbreviated to a&& (b); B can be a function call expression, or multiple statements are strung together with ",". However, if a is defined, an error will be made.

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" 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, enter as king! ", Nameerrortip is hidden  

returnRepresents the nameInput.length&&nameInput.val()&&nameErrorTip.length&&msg value that will be evaluated first nameInput.length if length the 0 expression is false, or true if True 1 . The same val() is true if the val() result is an "" expression that is also a false value. Between several expressions is an && operation, which means that the values of several expressions are evaluated sequentially, and if none of them returns the value of the last expression, because the entire expression "没有找到name输入框或者输入框没有值!" is an operation between the expression, one of || the preceding expressions is a false value to return || The value of the expression on the right, which is the entire “没有找到name输入框或者输入框没有值!” string.

Speaking of which, I have previously written an article specifically on && , || the truth, false value problem. Interested can go and have a look.

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!

Source: http://www.tashan10.com/

Twilight into Snow Blog

(function ($) {}) (jQuery) data records

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.