D
D
Denis2015-11-15 18:23:24
JavaScript
Denis, 2015-11-15 18:23:24

Counter in native JS?

Hello. The essence of the question is that I would like to implement the function of calling the counter in native js without brackets, that is, when we call the function, we specify brackets, because otherwise it will not be executed. For example:

function makeCounter() {
var curent = 1;

return function() {
return current++;
}
};

var counter = makeCounter();
counter();
counter();

alert(counter()); // даст нам значение 3

So is it possible to organize so that counter is called without parentheses? I have also tried implementing this with a constructor:
function makeCounter() {
var curent = 1;
 return {
    get: function() {
      return curent++;
    }
}
};

var counter = new makeCounter();
counter.get();

But in this case, the design becomes even more complicated. And I would like to get just a call to counter without parentheses.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Taratin, 2015-11-15
@den0820

https://jsfiddle.net/QW01_01/w45v1hdc/1/

var makeCounter = function(counterName){
  var c = 0;

    Object.defineProperty(window, counterName, {
      enumerable: false,
      configurable: false,
      get:function(){
          return c++;
      }
    });

}

makeCounter('counter');

counter;
counter;
counter;

console.log(counter);

K
Konstantin Kitmanov, 2015-11-15
@k12th

It can be easier.

function Counter () {
    var _counter = -1;
    return {
        valueOf: function () {
            _counter++;
            return _counter;
        }
    }
}

var cnt = new Counter();
alert(cnt);
alert(cnt);

There are variations, but the essence of the trick is in valueOf (sometimes they use toString, but in fact valueOf is needed).

E
Evgeny Korolev, 2015-11-15
@eakorolev

You've been shown two main options: use a getter or override valueOf/toString. But such an implicit change to the object on each call may not work as you expect. Be careful when using such "cheat" solutions, and be sure to document such code. If I saw this in public code, I would be upset :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question