I have some third-party Javascript that has statements like this:
FOO = function() {
...functions() ...
return { hash }
}();
It is working as designed but I’m confused by it. Can anybody define what this structure is doing? Is it just a weird way to create a class?
This is a technique that uses closure. The idiom is well-known, but confusing when you first see it.
FOOis defined as the object that the outermost function() returns. Notice the parenthesis at the end, which causes the function to evaluate and return{ hash }.The code is equivalent to
So FOO is equal to
{ hash }. The advantage of this is thathash, whatever it is, has access to stuff defined inside thefunction(). Nobody else has access, so that stuff is essentially private.Google ‘Javascript closure’ to learn more.