function makeCounter() { var currentCount = 1; // возвращаемся к функции function counter() { return currentCount++; } // ...и добавляем ей методы! counter.set = function(value) { currentCount = value; }; counter.reset = function() { currentCount = 1; }; return counter; } var counter = makeCounter(); 

  • In this particular case, everything is fine, because there are no intersections of scopes, but it is better to avoid similar situations and call the variable in the last line counterInstance - Alexandr Tovmach
  • @AlexandrTovmach, what do you mean by intersection ? var counter in the outer area and it is quite visible inside makeCounter , so there is a good intersection. - Grundy
  • @Grundy In this case, it does not matter, since the declaration of a global variable occurs after the internal function with the same name is declared. No intersection. - Alexandr Tovmach

1 answer 1

The language allows you to name variables as you like, in accordance with the rules.

The value associated with the name will be searched sequentially in areas of visibility until a match is found, or until nothing is found including in the global area.

Therefore, in this case, such a naming is quite acceptable.

From the point of view of the developer, it is better to give more meaningful names, so that then the variable is not confused for what is responsible.

  • var counter = makeCounter (); makeCounter () returns the result counter; it turns out var counter = counter will be correct? - xes
  • @xes, you think wrong when you do var counter = makeCounter() - this does not mean var counter = counter - Grundy
  • that after return returns () means to return the result and the function returns counter - xes
  • @xes, I do not understand what you are writing, just a set of words is obtained. - Grundy
  • the function in brackets () returns the result; returns return in another way - xes