简体   繁体   中英

Self Executing Anonymous Functions within Javascript

I have been trying to understand anonymous functions. I have come to realise that adding extra parentheses at the end helps the anonymous functions execute. However, I have also come across code that seems to execute the anonymous function without the extra parentheses, and to my surprise I couldn't find the use of the jquery ready method either. It goes something like :-

$(function() {

    $('#login_form #username').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#login_form #username').text('Thanks');
        },
        error: function() {
            $('#login_form #username').text('Plese fill username field');
        }
    });

});

The above file is simply included in an html file containing a form. I can't seem to understand how the above code is being executed automatically. Can somebody help shed some light on this ? Also, what difference would the extra parentheses make, such as :-

$(function() {

    $('#login_form #username').validator({
        format: 'alphanumeric',
        invalidEmpty: true,
        correct: function() {
            $('#login_form #username').text('Thanks');
        },
        error: function() {
            $('#login_form #username').text('Plese fill username field');
        }
    });

})();

$ is a function in jQuery. So, $() is a function call. And:

$(function() { /* code here */});

is a function call that you are passing an anonymous function to. That $ function will then call that anonymous function at some time in the future. In jQuery's case, it will call that function when the DOM is done loading and ready for manipulation. It's a shortcut syntax that I don't use primarly because it confuses people that aren't familiar with jQuery, but others like it for its brevity. It is shorthand for this:

$(document).ready(function() { /* code here */});

which I personally find a little more self-descriptive.

These are NOT self-executing anonymous functions. Those are a different construction for a different purpose. This is just a plain function call just like ready() would be, with the one addition of passing it a function.

The extra parens on your second construction are not needed and don't add anything in this particular case.

You are just calling a function with a specific name. The name of the function is $ . If you will do something $() in the debugger you will see that it will execute it. You can pass a parameter to this function.

In your case your parameter is a function. But you can do something like this: $(console.log(1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM