0

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?

2 Answers 2

2

The term you are looking for is (en)Closure

ignore the en

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

Comments

0

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.

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.