Friday, 15 July 2016

Javascript Code Structure - How Does This Work?




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);

Answer



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
};
}());

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...