Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Code Structure - How Does This Work? [duplicate]

Tags:

javascript

I've stumbled upon a pretty elegant way to structure JS Code for a page, though I'm not really sure why it works the way it does. Could someone explain to me how this works? (Why is that return statement there for example).

Also is there a name to describe a pattern like this?

var PageCode = (function () {

    return {
        ready: function () {
            console.log('document.ready');
        },
        load: function() {
            console.log('document.load');
        }
    };
}());

$(document).ready(PageCode.ready);
$(window).load(PageCode.load);
like image 578
richie Avatar asked Aug 08 '26 01:08

richie


2 Answers

The pattern is called Revealing Module Pattern, a variation of the Module Pattern where the return value is used to expose properties of the module to make them public.

The advantage in returning some values at the end is that you can define all variables and functions in the same way using var, instead of making them properties of the module. The returned object contains some of the previous defined variables to make them public (unlike in your example where the functions are defined in the return statement)

In the standard Module Pattern you would define private and public function like this:

var PageCode = (function () {

    var f1 = function() { /* ... */ }
    this.f2 = function() { /* ... */ }

}());

And for the Revealing Module Pattern the equivalent would be

var PageCode = (function () {

    var f1 = function() { /* ... */ }
    var f2 = function() { /* ... */ }

    return {
        f2: f2
    };
}());
like image 174
kapex Avatar answered Aug 10 '26 13:08

kapex


To help you understand this code , look at what goes after the return statement as an object

{
    ready: function () {
        console.log('document.ready');
    },
    load: function() {
        console.log('document.load');
    }
}

an object that has two items which are both functions. this object is returned and assigned to the variable PageCode, now you can call the frist function PageCode.ready(); and the second PageCode.load();

The $(document).ready(); and the $(window).load(); functions take as arguments functions, which are going to be executed when the document is ready and when the window is loaded. that's why you call them with functions as arguments

$(document).ready(PageCode.ready);
$(window).load(PageCode.load);
like image 39
Khalid Avatar answered Aug 10 '26 14:08

Khalid



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!