1

Is there any benefit for the following JavaScript module defenition:

 var module = (function(){

 var PublicFnc = function(){ // variable declaration 
     alert('hi');
 }

 return {
   f : PublicFnc
 }
 })();

 module.f();

Over the following:

 var module = (function(){

 function PublicFnc(){ // function declaration 
     alert('hi');
 }

 return {
   f : PublicFnc
 }
 })();

 module.f();

Although the second example is more convenient since it is more similar to Java/C# the anonymous methods are used more often and I'm wondering what is the benefit?

@Alexander, thanks for marking the question as duplicate but I tend to leave it open since I'm asking for the benefits within the context of module patterns and not generally

matisetorm
  • 857
  • 8
  • 21
Shadi Shaaban
  • 1,670
  • 1
  • 10
  • 17

1 Answers1

2

One of the differences between them can be explained using a concept called hoisting

In case:

a(); //you cannot call this function before its definition as here var a is undefined

var a = function(){ //function statement
    console.log("Hello World");
}

a(); //this will call the function even before its definition because of hoisting

function a(){ //function definition
    console.log("Hello World");
}

Also some the function in the above case is assigned a memory space using that variable.

In hoisting, function definition is hoisted and not the function statement.

Read more about hoisting here http://www.w3schools.com/js/js_hoisting.asp

Also, when to use statement and when to use definition depends on use case and personal preference

NehaJ
  • 127
  • 6