The thing that calls displayResults
controls data
not only when the the function is called but also when it returns (and hence before your callback gets called). The calling sequence could look like this:
data = { /* interesting things */ };
displayResults(data);
delete data.queryType;
// Time passes and then your callback gets called
// but data.queryType is undefined.
I don't know the exact circumstances of your situation but the above summarizes what can happen.
When you produce a closure over data
you're grabbing onto data
but that doesn't mean that you've locked what's inside data
.
Now that we know where data
is coming from and why it was broken in the first place, we can consider why it works when data
is correct and left alone.
When you create your anonymous callback function:
function() {
alert(data.queryType);
return false;
}
you're creating a closure that holds onto a reference to data
(or, more accurately, what data
points to) and data
won't be killed off until no one is referencing it. The lifetime of a variable depends on its scope; your data
variable has lives within your displayResults
function. But the variable only references (or points to) an object in memory and that object will, more or less, stick around until no one references it anymore.
The variable name and the object that is named are separate entities with separate lifetimes. To quote Bruce Lee:
Don't concentrate on the finger, or you will miss all the heavenly glory.
You can't get away from pointers in programming even when they're not called pointers.