Lewis Knight Lewis Knight - 5 months ago 9
jQuery Question

What's this type of jquery coding style called?

I've always used jquery with a

$(document).ready(function {
....
});


But i've recently just inherited a complete site with the script file opening like the following:

var gc = gc || {};

gc.header = {

mobileNav: function () {
...
},

headerLink: function () {
...
}
};

gc.header.headerLink();


I've never seen it structured in this way - it's actually quite easy to use and would love to learn more about to help improve my coding styles.

If somebody could help me by providing me with what this type of coding style is? And - if you know of any, some learning resources?

Thanks in advance!

Lew.

Answer

This style of JavaScript syntax is a little more object oriented. This makes it easier to edit and read but also helps your JavaScript stay 'clean' by namespacing your JavaScript. This means that you basically try to keep as much of your JavaScript out of the Global Object as possible - thereby reducing collisions in your code.

Line by line:

var gc = gc || {}; // If a 'gc' object exists, use it. Otherwise create an empty object.

gc.header = { // In the gc.header object create 2 methods, mobileNav and headerLink

    mobileNav: function () {
        ...
    },

    headerLink: function () {
        ...
    }
};

gc.header.headerLink(); // Reference the headerLink() method inside gc.header

This is far preferable to creating a more flat pattern where mobileNav and headerLink are global functions because mobileNav and headerLink are very generic functions that may be used and named identically in other plugins. By namespacing you reduce the risk of breaking your code and running into collisions because gc.header.headerLink() is much more unique.