1

The below snippet throws unexpected token at line: b: function (func, data1) https://jsbin.com/qobicahica/edit?html,js,output

var Funcb = (function()
{
return 
{
    b: function (func, data1)
    {
        alert(1);
    }
};
    })();

Funcb.b(1,1);

But, a similar example in below tutorial works:

https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/

    // define module
    var Module = (function () {
  return {
    myMethod: function () {
      console.log('myMethod has been called.');
    }
  };
})();

// call module + methods
Module.myMethod();

EDIT: Works after removing linebreaks after return, But why? When javascript is so forgiving and loosely typed, then why is this not ignored?:

var Funcb = (function()
    {
    return{
        b: function (func, data1)
        {
            alert(1);
        }
    };
        })();
Stacky
  • 381
  • 2
  • 5
  • 18

2 Answers2

2

The problem is on the third line, a semicolon is inserted after the return statement. See the rules for JS automatic semicolon insertion.

Remove the newline character after return and it should work.

var Funcb = (function() {
    return {
        b: function (func, data1) {
            alert(1);
        }
    };
})();

Funcb.b(1,1); 

To answer your EDIT, see page 28 of the specs.

The source

return
a+b

is transformed by automatic semicolon insertion into the following:

return;
a+b;

The expression a+b is not treated as a value to be returned by the return statement, because a LineTerminator separates it from the token return.

Community
  • 1
  • 1
Tomas Nikodym
  • 8,782
  • 3
  • 15
  • 17
1

Your return statement should contain something. The curly brace is on the next line and should be next to the return statement. This is giving the unexpected token error.

var Funcb = (function() {
    return {
        b: function (func, data1) {
           alert(1);
        }
    };
})();
Funcb.b(1,1);
  • Thanks for checking. Found after posting, edited the question. When javascript is so forgiving and loosely typed, then why this is not ignored? – Stacky Sep 17 '16 at 18:51
  • 1
    Because in your example the function is returning null (an empty return statement), and then the parser tries to evaluate the {b: func..} object which is not assigned. – Robbert Helling Sep 17 '16 at 18:56