1

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.

Lew
  • 41
  • 5
  • This is called object oriented programming. The object is `gc` and it has methods (the functions) and can also have properties. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript – Ike10 Jun 16 '16 at 15:01
  • 3
    The 2 have absolutely nothing to do with each other – devqon Jun 16 '16 at 15:02
  • 3
    Please learn about coding JavaScript outside the confines of jQuery. – Heretic Monkey Jun 16 '16 at 15:02
  • The jQuery one defines scripts to run when the page has loaded, the second just defines a way of building an object. Unrelated in terms of functionality im afraid. – ste2425 Jun 16 '16 at 15:03

3 Answers3

5

It is usually referred to as namespacing. It has absolutely nothing to do with jQuery.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

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.

Andrew
  • 106
  • 3
1

It`s just ordinary JavaScript, it's a technique called namespacing: How do I declare a namespace in JavaScript?

Community
  • 1
  • 1
Felipe Guerra
  • 145
  • 13