Answer the question
In order to leave comments, you need to log in
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
function makeCounter() {
var curent = 1;
return {
get: function() {
return curent++;
}
}
};
var counter = new makeCounter();
counter.get();
Answer the question
In order to leave comments, you need to log in
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);
It can be easier.
function Counter () {
var _counter = -1;
return {
valueOf: function () {
_counter++;
return _counter;
}
}
}
var cnt = new Counter();
alert(cnt);
alert(cnt);
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 questionAsk a Question
731 491 924 answers to any question