0

Hi I am new to javascript and I am trying to maintain someones code, but I cant seem to figure out what they are doing.

They seem to be declaring a function like so:

(function(Module) {
    Module.register(...) {
       ....
       return ...;
    };
    Module.register(...) {
       ....
       return ...;
    };
 }(hb.Core));

If you wanted to create a function that called Module.register twice (which is what I think they are trying to do), wouldn't you do the following?

function myFunction(Module) {
     Module.register(...) {
        ...
     };
     Module.register(...) {
        ...
     };
}
myfunction(Module);

Also, don't know if this is really relevant, but they are using the sandbox model (where they have different modules communicate with the application core only through a sandbox).

Hope someone can help out. I am really new to Javascript and front-end development in general and I am very confused.

user2158382
  • 4,430
  • 12
  • 55
  • 97
  • From what you've shown us, the first section does look like a mistake. – Ben McCormick Mar 19 '13 at 17:58
  • Have you looked at http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work – ddavison Mar 19 '13 at 17:58
  • 2
    By wrapping the function in parenthesis, a function expression is created, which doesn't pollute the global scope. – Shmiddty Mar 19 '13 at 17:58
  • With the first code, your guy was trying to load the module code before the DOM was ready,and also preventing it from be lost in global space by placing it in self-invoking function. So that code gets executed right away. – klewis Mar 19 '13 at 18:02
  • Hi @user2158382 and welcome to StackOverflow. The answers you are receiving are useful enough to try to improve them. Maybe you'll find helpful [that slideshare](http://www.slideshare.net/ericshepherd/building-a-javascript-module-framework-at-gilt), will be very pleasant and good for your training – Áxel Costas Pena Mar 19 '13 at 18:02

2 Answers2

2

Duplicate What is the purpose of a self executing function in javascript?

it's a self executing anonymous function call. your example is a function declaration where you've assigned the function a name so it is no longer anonymous. self executing functions are used when there is a need to scope your variables to only be available to anything in side the self executing function.

Community
  • 1
  • 1
iAmClownShoe
  • 606
  • 1
  • 4
  • 10
0

If you mean that function

(function(Module) {}(hb.Core));

It is a self invoking function receiving hb.Core value for its Module parameter. In javascript functions declare scopes so this is the primary reason for the one above.

The variable inside that function are not accessible outside of it , which means outside of it's scope