2

Say you have [Fiddle]

function TestMethod() {
    var lifespan = "blah";

    $.ajax({
        url: "http://www.google.com",
        success: function (data) {
            alert(lifespan);
        },
        error: function (errorData) {
            alert(lifespan);
        },
        dataType: 'html'
    });
}

Why is it that lifespan still exists when the callback fires? What else persists through asynchronous calls? What allows this to happen, is there some kind of "runtime" ,if you will, in javascript that keeps code alive during the process? If so, when does it know when to start letting in memory items die?

1

3 Answers 3

5

Javascript has function scope, not block scope (curly brace) like C, C++, C#, PHP, and Java.

Here is the jsFiddle example -

http://jsfiddle.net/Wrz6X/

Sign up to request clarification or add additional context in comments.

2 Comments

+1 This helps, great call on Fiddle. I need to remember to use that site in the future.
I see a lot of votes coming in on this answer and not closure. Why? Is the community saying the reason is "function scope" and not closure?
4

You need to read about javascript closures. All variables within the scope of an embedded function (whether declared in parent functions or not) stay available until all references to the closure inside of the function is done executing.

Since I was originally a C/C++ developer, I think of it like garbage collection for stack frames. The stack frame of any function isn't disposed of when the function is done executing, but rather when all references to it have been released. Embedded/internal functions that are still not yet complete (like your ajax callbacks) hold references to the containing stack frames and thus they are still available until those embedded functions themselves are done, even though the containing function has finished executing.

Once you understand it, it's very, very, very useful and a great feature that other languages like C/C++ don't have. It makes local variables useful in more circumstances.

1 Comment

+1 I'm still a bit of a js noob, but I have "javascript the good parts" on order.
3

That's one of the fundamentals of javascript. closures (lambda functions) inherit variables from the scope in which they were defined in.

And it helps overcoming many problems that come with an asynchronous, event based language.

function foo() {
    var privateMsg = 'blah...';

    setTimeout(function(){
        alert('private msg: ' + privateMsg);
    }, 5000);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.