views:

63

answers:

3

Hey guys,

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();
 }) (); 
}) ();
+3  A: 

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.

Gabi Purcaru
A: 

"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.

VoteyDisciple
A: 

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.

Frank Hellwig