What type of function is the following and which is their best use?
var f = function (){
var a = 0;
return {
f1 : function(){
},
f2 : function(param){
}
};
}();
I tried to convert it to:
var f = {
a : 0,
f1: function (){
},
f2: function (param){
}
}
But seems does not works the same way.
It’s just a plain old function that is invoked immediately, and returns an object which is then referenced by
f.The functions referenced by object returned retain their ability to reference the
avariable.No code outside that immediately invoked function can reference
aso it enjoys some protection since you control exactly what happens toavia the functions you exported.This pattern is sometimes called a module pattern.
Regarding your updated question, it doesn’t work the same because
ais now a publicly available property of the object.For the functions to reference it, they’ll either do:
or if the function will be called from the
fobject, they can do:Like this:
But the key thing is that
ais publicly available. Any code that has access tofcan accessf.aand therefore make changes to it without using yourf1andf2functions.That’s the beauty of the first code. You get to control exactly what happens to
a.