H
H
HellishCode2019-05-23 09:02:53
JavaScript
HellishCode, 2019-05-23 09:02:53

Is this example a closure and why YES or NO?

Hello, what do you think, can this counter function be a closure and why YES or NO?

let count = 0;

function counter() {
  return count += 1;
}
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shvets, 2019-05-23
@HellishCode

Absolutely any function in js forms a closure.
It's just empty sometimes. And the engines are also engaged in optimization and remove unused links from the scope.
But there is such a definition of a closure, when only a function declared inside another function can be considered a closure. And there is already room for ambiguity.

I
Ilya, 2019-05-23
@ilyapashkov02

No

S
Sergey Sokolov, 2019-05-23
@sergiks

Mozilla defines closures like this:

A closure is a combination of a function and the lexical environment in which the function was defined.
A closure is the combination of a function and the lexical environment within which that function was declared.
If these introductory descriptions are counted as "correct" definitions, then formally "YES" is, albeit degenerate. In your example, this environment coincides with the global environment, so there is no question of any imitation of private methods and properties.
To make a kosher closure, you need to properly wrap this code so that no one from outside could get into the privacy of its variables:
function makeCounter() {
  // далее ваш код:
  let count = 0;
  function counter() {
    return count += 1;
  }
  // конец вашего кода.

  return counter; // вернули Функцию (с её окружением)
}

var myCounter = makeCounter();
// вот теперь к значению count не добраться - приватность!
// зато
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question