When you see code like this:
var spa = (function () {
..
..
return { initModule: initModule };
}());
Can someone explain the line return { initModule: initModule }
?
When you see code like this:
var spa = (function () {
..
..
return { initModule: initModule };
}());
Can someone explain the line return { initModule: initModule }
?
It's a revealing module pattern (well, almost - your syntax is slightly wrong). You define the module in the function (including all 'private' methods and variables) and then return an object containing only those methods you want in the API. In this case there's only one method: spa.initModule().
It should look like:
var spa = (function () {
function initModule() {
//do something
}
return { initModule: initModule };
}());
spa
is actually an object, not a function. The function is only returning the module API to spa
. So you define initModule
in the function but to return it you need to add it as a value in an object. Assuming you want the same method name on spa
you use the key name initModule
too.
You can see in the demo that in the second example I've used hallo
as the object key name.
First
(function () {})();
is anoynomous function and will be executed when script is processed
{}
is object literel in javascript
Overall
spa will contain an object reference to { initModule: initModule }
spa.intiModule
will return its value whatever is set. if initModule
is function reference then it will return reference to function and you have to call spa.intiModule()
to execute it
It's a revealing module pattern. See the following syntax.
var spa = (function () {
..
..
function initModule () {
// Your code
}
function otherModule () {
// Your code
}
return { initModule: initModule };
}());
Every variable function defined inside spa
object will not be directly accessible.
In module pattern if we return spa
as a whole object, then we've to define which function/ variables will be returned.
So, our code for initModule
will be
spa.initModule = function () {};
In revealing module pattern, we just return a single object which contains all the variables and functions available to user using spa
object.
The return { initModule: initModule }
line actually tells the spa
object's function called initModule
(defined 2nd time) is available outside this module. The first time initModule
is called is the name by which it can be accessed.
This is equivalent to return { test: initModule }
. Now you've to call spa.test()
to execute initModule
inside it.