Differences in jquery $ (function () {}) and (function ($) {}) (jquery), $ (document). Ready (function () {}) detailed explanation

Source: Internet
Author: User

1. (function ($) {...}) (JQuery);

1), principle:

This is actually an anonymous function, as follows:

Function (ARG) {...}
This defines an anonymous function with the argument arg

When calling a function, the parentheses and arguments are written behind the function, and because of the precedence of the operator, the function itself needs parentheses, namely:
(function (ARG) {...}) (param)
This is equivalent to defining an anonymous function with arg parameter, and calling this anonymous function as a parameter param

(function ($) {...}) (jquery) is the same, the reason that the only use of $ in formal parameters is to not conflict with other libraries, so the argument uses jQuery
Equivalent to funtion output (s) {...};output (jQuery); or Var fn=function (s) {...}; FN (jQuery);

2), function (very useful):

The greatest advantage of this writing is the formation of closures. In (function ($) {...}) (jQuery) functions and variables defined internally can only be valid in this scope.

the concept of whether a function function or a private variable is formed. For example:

var i=3;
function init () {
    alert ("Outer init:" +i);
(function ($) {
	var i=2;
	function init () {
	    alert ("Inner layer init:" +i);

	Init ();
}) (jQuery);
Init ();

Execution results:

Inner layer Init:2

outer Init:3

2, $ (function () {...});  JQuery (function ($) {...}); $ (document). Ready (function () {...})

These three functions are the same, I need to use the first one, simple writing.

The function to execute after the document is loaded.

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.