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);
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.
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.
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.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With