开发者

Event Listener and AJAX asynchronous function variable scope

开发者 https://www.devze.com 2023-02-16 16:02 出处:网络
I got a question, probably very simple, but whatever. When registering an event listener inside an asynchronous function, I would believe that all values within that function would be non-existing whe

I got a question, probably very simple, but whatever. When registering an event listener inside an asynchronous function, I would believe that all values within that function would be non-existing when the function has run it's course.

However, an event listener, as displayed below in the code can still access the variable values, how is that? Is the variable saved within the event listener somehow?

$.ajax({
    type: "GET",
    cache: false,
    url: "/whatever",
    success: function(data) {
        var values = ["Some Values", "Inside this Object"];

        $("#id :checkbox").click(function() { 
            var allValues = [];

            $('#id3 :checked').each(function() {
                allValues.push($(this).val());
            });

            $("#id2").val(allValues);

            callMe.init(values,allValues);
        });
开发者_如何转开发    }
});


This is because of closures. A function "closes over" all variables in its lexical scope, which is to say that it retains access to them once the function in which it was defined has returned.

In your specific example, values is in scope when the function given to click is defined, so it will remain accessible even once success completes.

You'll find a lot more information here:

  • How do JavaScript closures work?


The JQuery $ sign is in the global scope. Anything can reference it. You are reaching the form checkbox values through $.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号