Javascript closure - what is the difference between these

EDIT

With the number of answers saying "you can do personal things!" below, I will also add this to the beginning:

I know that you can emulate private variables in closure. This is not what I am asking for. I ask, given the two examples below, where I “export” ALL from closure, what is the fundamental difference between the two examples.

Given these two methods of creating objects / methods:

var test = {}

test = (function(){
    var a_method = function(print_me){
        return "hello "+print_me;
    }

    return {print_me: a_method};
})();

test.print_me2 = function(print_me2){
   return "hello "+print_me2;
}

test.print_me('world');
>>> returns "hello world"

test.print_me2('world');
>>> returns "hello world"

I understand that the first method allows you to use private variables (which, as a python developer at heart, I really do not need), but both seem pretty indifferent to me, only the first one looks “colder” (as in all big javascript people seem to do it that way), and the second way looks very skipping & eacute;

, , ?

- , ; , , .

- " , ", " , Mozilla , ", "", .

+5
3

- , , , , .

. , :

var test = {
  print_me: function(text) { return "hello " + text; }
};

:

var test = {};
test.print_me = function(text) { return "hello " + text; };

:

function Test() {}
Test.prototype.print_me = function(text) { return "hello " + text; };
var test = new Test();

Javascript , , . , .


, , :

test.print_me2 = (function(){

  var method = function(print_me2) {
    return "hello "+print_me2;
  }

  return method;
})();
+3

, .

var thisIsGlobal = 2;
var test = (function () {
  var thisIsLocal = 3;
  return function () {
    return thisIsLocal;
  };
}());

, , test, thisIsLocal. . .

+2

The first method that you present (an anonymous function that executes immediately) takes your program out of the global scope. Within this private area, you can decide which properties you want to use as your API:

(function(win){
  var a, b, c = 1;  

  function init(){ 
    return aa(b);
  }

  function exit(){
    if(cc()){
      return a;
    }
  }

  function aa(){
  }

  function bb(){
  }

  function cc(){
  }

  win.myProgram = {init: init,
                   exit: exit };
})(window);


// We now have access to your API from within the global namespace:    
myProgram.init();    
//etc
0
source

All Articles