Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: which function structure to use

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();
 }) (); 
}) ();
like image 646
Frank Parent Avatar asked Oct 13 '22 22:10

Frank Parent


2 Answers

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.

like image 131
Gabi Purcaru Avatar answered Oct 16 '22 16:10

Gabi Purcaru


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

like image 43
VoteyDisciple Avatar answered Oct 16 '22 15:10

VoteyDisciple