Reputation: 33715
i forgot the term used in javascript to describe a particular phenomenon. It's related to the way variables are accessed in inline functions. I don't quite understand the theory either. I vaguely recall the following code
for(var c = 0; c< 10; c++)
{
arrayOfObjects[c].onclick = function() {alert(c); };
}
And I remember when clicking on an object, the alert window always printed 10. Then someone explained it's because everything in javascript is an object. Even function(){blah} is an object that gets evaluated at run time, and that's why I'm getting confused with variable scope.
I think the term to describe this phenonmenon started with the letter e. it was something like enveloping, or encapsulating, or entrapping, or something like that.
what's the term I'm looking for?
Upvotes: 0
Views: 143
Reputation: 17821
In your example code, an effective CLOSURE might look like:
for(var c = 0; c< 10; c++) {
arrayOfObjects[c].onclick = function(cc) {
// cc is sustained in here
return function () {
alert(cc);
}
}(c);
}
The outter function is executed immediately, thanks to the ()
at the end, and 'c' is passed into it as 'cc'. The inner function is then 'constructed' and returned for the onclick. When this stored inner function executes later, it will still have a reference to the 'cc' as it was at the time of its construction.
Upvotes: 0