I often see this pattern:
var suchAndSuch = new (function() {
this.thing = "something";
this.whoaLookAtThat = function() {
return 4;
}
return {
'thing' : thing,
'whoaLookAtThat' : whoaLookAtThat
}
})();
What is going on here? It's the return
statement part that confuses the hell out of me.
I just don't get this particular use of an IIFE.
If nothing else, knowing what it's called would help me research it.
This is a combination of an immediately executing function and a (bit of a messed up) closure. I think your example maybe a bit flawed it may be better if it was:
var suchAndSuch = (function() {
var thing = "something";
function setThing(newThing){
//maybe do some error checking here
thing = newThing;
};
function getThing(){
return thing;
};
return {
getThing : getThing,
setThing : setThing
}
})();
Then you would have a function that executes immediately returning a new object that effectively gives a private variable and an accessor function. I have used constructs like these many times.
This is kind of an attempt to have public/private variables in JavaScript... I believe it is referred to as the modular pattern.
var suchAndSuch = (function() {
var privateVariable = "something";
var privateFunction = function() {
return 4;
}
return {
publicMethod1: function() {
return privateVariable;
},
publicMethod2: function() {
return privateFunction();
}
}
})();
Basically any variables declared inside the IIFE will be private. Then you return an object with methods. Since the object/methods were defined in the same scope as the private variables, the methods still have access to them. However, nothing else will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With