0

I have the following class:

var myclass = (function(){
   var b={};

   b.method1 = function(){
       console.log("method1");
   };

   b.method2 = function class2(){
       console.log("method2");
   };

   return b;
}());

Is there any difference between these methods other than that method1 is anonymous functions assigned to method1 and method2 is a named function?

I usually use the method1 way but just discover method2 for method declaration.

And are there any advantages to use one over the other?

Broxzier
  • 2,909
  • 17
  • 36
curvenut
  • 85
  • 2
  • 11
  • possible duplicate of [How to use Revealing module pattern in JavaScript](http://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript) – Jeremy J Starcher Aug 21 '13 at 21:28
  • method2 shows "class2" in an error log, but method1 shows "anonymous", which do you find more helpful? – dandavis Aug 21 '13 at 21:30
  • Just a side note: You could use `this` instead of `var b`, and get rid of the return statement. – Broxzier Aug 22 '13 at 07:54

3 Answers3

1

For a named function expression(method2) you can call the function within itself by its name.

b.method2 = function class2(){
   console.log("method2");
   if (somecondition){
       var something = new class2();
   }
};
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Actually, the name can be used not only to call the function, but also to refer to itself in a more general way. – pedromrnd Aug 21 '13 at 21:54
0

Functional this is nearly the same. On some Browsers you can see a difference if you call console.log( b.method1, b.method2 ) because the second one has a name. There is a variety of articles on this topic here. This is one of them: What is the difference between a function expression vs declaration in JavaScript?

Community
  • 1
  • 1
Scheintod
  • 7,953
  • 9
  • 42
  • 61
0

A function name in JavaScipt is basically a variable, so you can reuse it. This means you can use class2 within your self-executing function without calling b.method2. Since your self-executing function returns your b Object, you can't use class2 outside.

Saic Siquot
  • 6,513
  • 5
  • 34
  • 56
StackSlave
  • 10,613
  • 2
  • 18
  • 35