There can be anonymous functions in jquery, and the definition syntax is "(function($){...})(jQuery)"; this statement uses the jquery object as an actual parameter, and the anonymous function will be automatically called and Pass parameters to an anonymous function as formal parameters of the anonymous function.
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
$(function(){ } is actually an anonymous function. This is the syntax of JQuery. $ represents the JQuery object, which can be used in several ways. For example, passing a selector Strings, page objects, etc., if you directly pass the function body in, it means that this function will be executed when the page is loaded.
This is actually the anonymous function "$(function(){ }", which defines a Anonymous function, the parameter is arg. When calling the function, brackets and actual parameters are written after the function. Due to the priority of the operator, the function itself also needs brackets, that is: "$(function(){ }" This is It is equivalent to defining an anonymous function with parameter arg, and calling this anonymous function using param as a parameter. "$(function(){ }" is the same. The reason why $ is only used in formal parameters is to avoid conflicting with Conflict with other libraries.
(funtion(){})(); Execute the function immediately; equivalent to declaring a function first and calling it directly after the declaration.
(function($){ } )(jQuery): Execute the (jQuery) function and use the jQuery object as an actual parameter. Then the anonymous function (function ($) {...}() will be automatically called and the actual parameters will be passed to the anonymous function as Formal parameters of anonymous functions.
(function ($) { alert("我执行了");})(jQuery);
is equivalent to
function callfunc($) { alert("我执行了");}callfunc(jQuery);
The execution result is as follows:
The example is as follows:
It is equivalent to defining an anonymous function with the parameter info, and when executing ("CoderZB"), passing CoderZB as a parameter will automatically call this (function (info) {}) anonymous function. The last one () is to call an anonymous function and pass parameters to the anonymous function
(function (info) { alert(info); })("CoderZB");
In fact, this is the form.
function infomationFunc(info) { alert(info); }; infomationFunc("CoderZB");
The example is as follows:
Video tutorial recommendation: jQuery video tutorial
The above is the detailed content of Can there be anonymous functions in jquery?. For more information, please follow other related articles on the PHP Chinese website!