a2net
8/26/2019 - 12:01 PM

Simple counter with private variables

Simple counter with private variables

// First example
function Counter () {
	let val = 0;
	return function () {
		return ++val;
	}
}

const b = new Counter();

for (i = 0 ; i < 10 ; i++) {
	console.log(b());
}

// LOG

// Console log
(index):41 1
(index):42 2
(index):43 3
(index):44 4
(index):45 5
(index):46 6
(index):47 7
(index):48 8
(index):49 9
(index):50 10
// Second example

const lala = (function () {
	let val = 0;
	return function () {
		return ++val;
	}
})();


for (i = 0 ; i < 10 ; i++) {
	console.log(lala());
}

// LOG
(index):41 1
(index):41 2
(index):41 3
(index):41 4
(index):41 5
(index):41 6
(index):41 7
(index):41 8
(index):41 9
(index):41 10