Does this incorporate JavaScript closures?

Posted by alex on Stack Overflow See other posts from Stack Overflow or by alex
Published on 2010-04-15T14:25:13Z Indexed on 2010/04/15 14:43 UTC
Read the original article Hit count: 259

Filed under:
|
|
|

In trying to learn JavaScript closures, I've confused myself a bit.

From what I've gathered over the web, a closure is...

Declaring a function within another function, and that inner function has access to its parent function's variables, even after that parent function has returned.

Here is a small sample of script from a recent project. It allows text in a div to be scrolled up and down by buttons.

var pageScroll = (function() {

    var $page,
        $next,
        $prev,
        canScroll = true,
        textHeight,
        scrollHeight;

    var init = function() {

        $page = $('#secondary-page');

        // reset text 
        $page.scrollTop(0);

        textHeight = $page.outerHeight();

        scrollHeight = $page.attr('scrollHeight');

        if (textHeight === scrollHeight) { // not enough text to scroll

            return false;    

        };

        $page.after('<div id="page-controls"><button id="page-prev">prev</button><button id="page-next">next</button></div>');

        $next = $('#page-next');

        $prev = $('#page-prev');

        $prev.hide();

        $next.click(scrollDown);

        $prev.click(scrollUp);

    };

    var scrollDown = function() {

        if ( ! canScroll) return;

        canScroll = false;

        var scrollTop = $page.scrollTop();

        $prev.fadeIn(500);

        if (scrollTop == textHeight) { // can we scroll any lower?

            $next.fadeOut(500);

        }

        $page.animate({ scrollTop: '+=' + textHeight + 'px'}, 500, function() {

            canScroll = true;

        });    

    };

    var scrollUp = function() {

        $next.fadeIn(500);

        $prev.fadeOut(500);

        $page.animate({ scrollTop: 0}, 500);    


    };

    $(document).ready(init);

}());

Does this example use closures? I know it has functions within functions, but is there a case where the outer variables being preserved is being used?

Am I using them without knowing it?

Thanks

Update

Would this make a closure if I placed this beneath the $(document).ready(init); statement?

return {
    scrollDown: scrollDown
};

Could it then be, if I wanted to make the text scroll down from anywhere else in JavaScript, I could do

pageScroll.scrollDown();

I'm going to have a play around on http://www.jsbin.com and report back

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures