Javascript - Why do method variables survive within a callback?
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?
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/
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.
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);
}
精彩评论