0
$.action = { do : function() { return 'im doing'; } }; function do() { return 'im doing'; } var action= function() { var do = function() { return 'im doing'; } return { init : function () { do(); } } }(); 

Calls :

$.actions.do(); do(); action.init(); 

Hola Amigos,

I am newbee..

There are a lot of usage of functions. But what is the difference between them ? What should i use ?

When i use first one, when i use second, when i use third ?

Thanks for advice...

3
  • 1
    It depends entirely on what scope you want the function to have. Either is useful for different scenarios, although I'd suggest that you shouldn't really add anything to the $ namespace. Commented May 9, 2018 at 12:32
  • 1
    The 2nd case is called the Revealing Module Pattern. I would recommend reading into it, and learning other common JS design patterns. Commented May 9, 2018 at 13:00
  • Thank you very much for unique information. Commented May 9, 2018 at 13:02

1 Answer 1

1

1st case is similar to the last case. It's an object that has some methods. The advantage of using the last example, is that you can have "private" variables and functions and you only expose what's necessary trough the returned object.

1st one also can be use for name-spacing. $.module1.do, $.module2.do

2nd case is just a function declaration. Useful when you want for example to write reusable, more general purpose functions.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.