PDA

View Full Version : Self fulfilling anonymous function



jscheuer1
07-26-2016, 08:17 PM
Not sure if this is the right term, but I sure don't mean a self executing anonymous function. This is a construct I think I saw years ago and never really got until now when I saw something (more complex of course) like it in a user's question:


(function(){
return {
init: function(){alert('Hello World!');}
}
})().init();

Pretty cool, eh? A private init, regardless of how many other "inits" there already might be. And, if the function isn't anonymous or self executing, it could be an alternate way of establishing prototypical properties. To wit (very simplified):


function afunction(){
return {
bob: function(){alert('I Am Bob');},
mary: 'Mary'
}
}
afunction().bob();
alert(afunction().mary);

In this second example, the number of properties returned by afunction would be virtually unlimited allowing for a privileged object that could only be overwritten by establishing an entirely new afunction function, or at least returning it, modifying it and then returning the new object.