Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
"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 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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question