0

My question is a little weird, I've got the following example code:

window.test = function (number) {
    $.ajax({
        url: "/test",
        success: function () {
            // console.log(number);
            console.log("test");
        },
        error: function () {
            // console.log(number);
            console.log("test");
        }
    });
};

test(5);

I dont really care if the AJAX call results with success/error, but I use the dev tools to place a breakpoint at each of the console.log statments, and then using the dev tools I try to inspect the value of number, either by hovering it, or by directly typing "number" into the console.

in all cases I get "undefined"

However if I remove the commented lines, ofc 5 is printed and when I stop at the breakpoint "number" is defined and has the correct value.

Question is.. Why?

From what I know each function should have access to its parent scope variables and so the success/error functions should have access to number.

My best guess is that because an AJAX call as been fired, by the time the browser gets to the callback "number" might have been collected by the browser GC.

Hacketo
  • 4,978
  • 4
  • 19
  • 34
Nir Cohen
  • 75
  • 7

1 Answers1

1

When you comment out the statements that use number from the callback functions, there is no longer anything in those functions which uses the variable.

The success and error functions do not close over number because they don't try to access it (and the JavaScript compiler can detect this).

Consequently when the test function finishes, the number variable is marked for garbage collection and not made available to success and error (which don't need it). This happens before success or error run (and you test the value of number in your debugger).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335