Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced Javascript initialisation

Tags:

javascript

I'm having trouble deciphering the following Javascript initialisation statement:

(function(NAMESPACE) {
        NAMESPACE.nav = {};
        var nav = NAMESPACE.nav,

_init = false,
        _isNavOpen = false,
        _inner = document.getElementById('inner-wrap');

    // constants
    nav.CLASS = 'js-nav-open';
    nav.CLASS_READY = 'js-nav';
    nav.CONTAINER = '#nav';
    nav.DURATION = 400;
    nav.HAS_CSSTRANSITIONS = $('html').hasClass('csstransitions') && $('html').hasClass('csstransforms3d');

... ...

// toggle open/close
    nav.toggle = function(event) {
        event.stopPropagation();

        if(_isNavOpen && $('html').hasClass(nav.CLASS)) {
            nav.close();
        } else {
            nav.open();
        }

        // this is for the links
        if(event) {
            event.preventDefault();
        }
    };

}(PROJECT_NAME));

It seems unnecessarily complicated - calling (or setting?) 'nav' 3 times in 2 lines. Can somebody please explain what the point is of flipping it around like this?

like image 682
timmackay Avatar asked May 23 '26 09:05

timmackay


1 Answers

This is an example of a JavaScript closure which is commonly used to create private scope and avoid having the objects pollute the global scope.

It is very common to create plugins this way to avoid conflicts with other functionality on the page as a result of variables with the same name etc. Essentially it's a mechanism for managing scope.

like image 97
TGH Avatar answered May 25 '26 23:05

TGH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!