I've been actively using the revealing module pattern for years but there's a few things I'd like to understand deeper. From what I understand potential benefits of self-executing functions are anoymimty & self-execution, both of which don't seem necessary/utilised in this particular pattern. The other thing I don't understand is, what in the below scenario makes its possible to wrap function Init inside the SocialMedia function(), i.e an embedded function, self-executing functions seem to be a very a unique construct in JS, isn't it strange that we can just assign a properties values to a self-executing code block?
var myObj = {
prop1, "prop1value",
SocialMedia: (function () {
function Init() {
}
return {
Init: Init
}
})()
}
Why do we use self-executing functions in the revealing module pattern?
JavaScript has first-class functions and lacks block-scoping, so functions are used to introduce new scopes.
what in the below scenario makes its possible to wrap function Init inside the SocialMedia function(), i.e an embedded function ... isn't it strange that we can just assign a properties values to a self-executing code block?
In JavaScript, a function is just an object that responds to the ()
and new
operators.
Like other objects, you can use it when you define it, or store it in a variable or property for later use.
self-executing functions seem to be a very a unique construct in JS
This isn't unique to JavaScript. All languages that have first class functions have this property, for example:
&
),In recent language development, first-class functions are the norm rather than the rule. Un-statically-typed languages just make it easier because there's no overhead in the type system syntax and no variance issues.
Even Java might be jumping on the bandwagon with Lambdas slated for Java 8.
In many of those other languages, immediately called functions aren't that useful though. Most other languages are block-scoped so if you want to keep your variables separate, you just use a {...}
block. In JavaScript though, var
is scoped to the smallest containing function
or Program, so function
s are the easiest way to introduce a new scope.
Ruby makes very little distinction between blocks and functions so could be considered similar to JS in this respect.