Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery anonymous function declaration meanings

Tags:

Are the following assumptions accurate?

1) execute immediately

(function(){ })(); 

2) execute on document ready

$(document).ready(function(){ }); 

3) shorthand for on document ready

$(function(){ }); 

4) alternative shorthand for on document ready for avoiding cross script conflicts

(function($) { })(jQuery); 
like image 513
Dr. Frankenstein Avatar asked May 28 '10 17:05

Dr. Frankenstein


People also ask

Can function declaration be a anonymous function explain?

The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions.

What is the meaning of anonymous function?

In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

How do you declare an anonymous function?

ES6 introduced a new and shorter way of declaring an anonymous function, which is known as Arrow Functions. In an Arrow function, everything remains the same, except here we don't need the function keyword also. Here, we define the function by a single parenthesis and then '=>' followed by the function body.

What is anonymous function give an example?

Next: Object-based programming. An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();


1 Answers

Yes your definitions are correct, for the first 3 :)

Though, unless you need a closure, a statement will execute immediately, no reason to wrap it like #1 has (there are certainly plenty of valid times you need a closure, just noting if you don't...it's superfluous).

Number 4 however is not correct, (function($) { })(jQuery); is not tied to any event, it's just a closure so that $ === jQuery inside of it, so you can use the $ shortcut:

(function($) {    //You may use $ here instead of jQuery and it'll work...even if $ means   //something else outside of this closure, another library shortcut for example })(jQuery); 
like image 77
Nick Craver Avatar answered Jan 02 '23 16:01

Nick Craver