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);
3
  • 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. Commented Apr 8, 2014 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. Commented Apr 8, 2014 at 22:00
  • Assigning the arguments to this would actually make things more complicated. You'd have to call "privateCheck" differently. Commented Apr 8, 2014 at 22:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What difference does the placement of the curly braces make? I have on on the next line.
@KingKongFrog Try it :) It's a weird corner of JavaScript syntax. It assumes that you forgot a semicolon after return in this particular case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.