D
D
Daniil Igorevich2016-01-24 19:35:29
JavaScript
Daniil Igorevich, 2016-01-24 19:35:29

Why is the function called without parentheses?

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();

alert( counter() ); // 1
alert( counter() ); // 2

counter.set(5);
alert( counter() ); // 5

I used to think that if a function is called without parentheses, then this is in order to show the code of the function, but in this case this is not so.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter, 2016-01-24
@petermzg

"return counter;" it's not a function call, it's returned by the object/function "function counter".
But further "counter()" is the call to this function "function counter()"

I
Ilya Pirozhok, 2016-01-24
@kamikadze1996

I will say this. Counter without brackets is a REFERENCE to a function \ object and counter(), that is, respectively, with brackets, this is the call itself. You return a reference to the counter function from the function and not its call, this is so that it can be called further in the code. And since it has a function = object and the methods that you assigned, here is also the rule, you only need a counter without parentheses so that you can call the METHODS of the object.
And after the scope of the function there are already parentheses. We want to increase the currentCounter =+ 1 variable, then we call the count () function. We want a reset or a method of this function, then we call counter.reset (). Otherwise, the result of counter().reset() would be

A
Alexey, 2016-01-24
@Rudmz

So alert( counter() ); and displays the result of the function execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question