Skip to content

Consider revising example 2.49 #5

Closed
@addyosmani

Description

@addyosmani

Original ticket:

I'm not sure example 2.49 is a good example to explain what a closure is.
It has a loop, which might be unnecessary, and a click event, which depends upon the user doing something, rather than simply running the program.

By breaking it out into three (3) distinct functions, I was able to step into (F11) it.
I mention F11 vs. F10 because I've grown used to using F10 to step over jQuery itself.

 function Function1() {
 var text = 'Hello '; // local variable
 var Function2 = function() { // Just because this was defined, doesn't mean it was run.
 alert(text); // text was declared outside of Function2
 }
 text = 'Goodbye ';
 return Function2; // In fact it won't run until Function3 is actually called.
}
 var Function3 = Function1(); // This gets back 'Function2' as a return, but doesn't run Function2
 Function3(); // This actually runs Function2

This helped me to realize that closures are simply variables that are kept after the function is completed, the same as 'static' variables are in Visual Basic.

Notes:

Another ticket that mentions this particular example should be revised is: https://github.com/rmurphey/jqfundamentals/issues/56, however they point out that we perhaps shouldn't be using jQuery in the example given it's the JS fundamentals chapter.

Dan appears to have provided a revised version of the example that's library agnostic here https://github.com/rmurphey/jqfundamentals/issues/56, however we should decide whether we want to stick to using jQuery in parts of this chapter or switch to vanilla JavaScript.

Leaving open for discussion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions