0

I have the following pattern however I'd like to know if I am thinking about this the right way. Do I need to assign the arguments to this? Is there anything you would do differently?

var myFunction = (function() 
{
    function privateCheck(a,b) 
    { 
        console.log(a+b);
    }
    return 
    {
        init: function(x,y) 
        {
            privateCheck(x,y);
        }
    }
})();

myFunction.init(3,4);
myFunction.init(4,5);
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • The code looks fine to me. Can you explain what you mean by "assign the arguments to `this`?" Also, `myFunction` is a what most people would call a module, so I would give it name that suggests it is an object/module. – aebabis Apr 08 '14 at 21:58
  • Thanks @acbabis. What I meant was assigning the vales to the object so I don't have to pass it into the privateCheck function. – KingKongFrog Apr 08 '14 at 22:00
  • Assigning the arguments to `this` would actually make things more complicated. You'd have to call "privateCheck" differently. – Pointy Apr 08 '14 at 22:01

1 Answers1

3

Your anonymous, immediately-invoked function will always return undefined. Your return statement trips over a common issue:

return { // <--- curly brace MUST be here
    init: function(x,y) 
    {
        privateCheck(x,y);
    }
}

Other than that it should be OK, though there's not much context.

edit the issue has to do with the often-weird rules about "semicolon insertion". In this particular case, like a handful of others, the language sees a newline after that return and assumes you just forgot the semicolon.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    What difference does the placement of the curly braces make? I have on on the next line. – KingKongFrog Apr 08 '14 at 21:56
  • @KingKongFrog Try it :) It's a weird corner of JavaScript syntax. It assumes that you forgot a semicolon after `return` in this particular case. – Pointy Apr 08 '14 at 21:57
  • @KingKongFrog http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi – Ian Apr 08 '14 at 21:57