5

I was reading an article about Javascript's best practices, and kinda got confused about which function structure to use...

I guess it might have an impact on the scope of the variables and functions, but which one of these structures would you use (and which is considered the best practice)?

Structure 1: use the object literals.

var obj1 = {
 _myvar : 'myval',
 init: function() {
 this.function1();
 this.function2();
 },
 function1: function() {
 alert('function1');
 },
 function2: function() {
 alert('function2');
 }
};
obj1.init();



Structure 2: Wrap the code in an auto-executing function.

(function(){
 var _myvar = 'myval',
 function1 = function() {
 alert('function1');
 },
 function2 = function() {
 alert('function2');
 },
 init = (function() {
 function1();
 function2();
 }) (); 
}) ();
asked Oct 12, 2010 at 18:02
1

3 Answers 3

3

You use the self-executing anonymous function when you don't want others to interfere with your code and/or don't want to use any global variable. If you might want to use those functions/objects/whatever somewhere else, you would want to use the first one.

answered Oct 12, 2010 at 18:06
Sign up to request clarification or add additional context in comments.

Comments

1

"Structure 1" is appropriate when you need access to the methods and variables in an object from other parts of your code. That format should always be your preference when you're writing library code that's meant to be reused elsewhere.

"Structure 2" is appropriate when you don't want to share your code with other parts of the application, and so you want to protect the variables and functions from any interference from elsewhere.

answered Oct 12, 2010 at 18:06

Comments

0

I have found Christian Heilmann's Revealing Module Pattern to be quite useful. (Scroll down to the last "green screen" code sample on his page.)

With is pattern, you can create all of your methods/functions privately in an anonymously executed function and then choose your public interface via the returned object.

answered Oct 12, 2010 at 22:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.