-1

I changed the last part of the question abit, as I found my mistake on the example I brought. Sorry for that.


While learning about JavaScript Module Pattern, as an example I saw code below:

var singletone1 = function() {
  function sayHello() {
    console.log("Hello")
  }
  return {
    sayHello: sayHello
  }
}()

This code works well as an example of revealing module pattern. But I realized that this makes the same result as IIFE version:

var singletone2 = (function() {
  function sayHello() {
    console.log("Hello")
  }
  return {
    sayHello: sayHello
  }
})()

The reason why I felt odd was that, as long as I know, running function declaration directly will make an error.

// Immediately Invoked Function Declaration
function(){  
  console.log('test');
}()
// => Uncaught SyntaxError: Unexpected token )

To run this, I have to embrace it with parenthesis. By that way, it becomes IIFE. But what is strange to me is the singletone1 example works as usual.

So my question is is there any difference on whether putting parenthesis between the function declaration or not? In other words, is there any difference between Revealing Module Pattern without parenthesis(singletone1) and IIFE version(singletone2)?

If they are same, then is that a matter of operator priority - so that the parenthesis are optional?

cadenzah
  • 928
  • 3
  • 10
  • 23

2 Answers2

0

Nice possible answer for this question:

"Explain the encapsulated anonymous function syntax"

So I conclude that the reason why singletone1 works properly with no problem at all and seems equivalent to singletone2 is because the statement on the right of the equal operator is interpreted as function expression, not function declaration, although it seems like declaration.

And also I learned that using anonymous function solely is not syntactically allowed, because sole anonymous function(without assigning to any variable) will be interpreted as function declaration, but function declaration must have name identifier. By this, I conclude that anonymous function can be used only after assigned to any variable, or used as IIFE.

If the situation is that a anonymous function can only be interpreted as function expression, then there is no need to put parenthesis around them. That can be optional in this case.

cadenzah
  • 928
  • 3
  • 10
  • 23
-2

Comments explain.

    var myLibrary = (function() {

        // reference document only once for performance
        var doc = document;

        // object to expose as public properties and methods
        var pub = {};

        //myLibrary.color
        pub.color = 'red';

        //myLibrary.hello
        pub.hello = function (name) {
            alert('Hello ' + name);
        };

        //API
        return pub;
    }());
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91