How to set a flag using a closure

Hi guys, I would like to set a flag using a closure so that the internal value of that closure is preserved for me to retrieve it when different events occur. It is one of those times where lack of block scope will stop me from doing what I want to do unless I can set a boolean and preserve its value in a function.

Can someone suggest the best way of doing this?

thanks

Silversurfer


var foo = (function() {
	var called = 0;
	return function() {
		return ++called;
	};
})();

alert(foo()); // 1
alert(foo()); // 2
alert(foo()); // 3

Ok thats great thanks very much, I can now do things like:


 if( foo() > 0)
{
// do something 
}
 

IS there any way of passing a boolean into the closure in the first place to update that value (true or false) every time you call it?


var foo = (function(val) {
	return function() {
		return val = !val;
	};
})(false);

alert(foo()); // true
alert(foo()); // false
alert(foo()); // true

Thanks so much oddz, I was a C++ developer and I am having some problems adjusting to no block scope and using closure instead of classes and private member variables, this has solved it! Have a great weekend :slight_smile:

Yeah, it is pretty cool when you get the hang of it in comparison to other languages. Closures are probably one of my favorite features of JavaScript.

Hi there I don’t seem to be able to get this function to return correctly, I know it returns true then false alternately but I can’t pass boolean parameters in ,

if I do:

foo(true); // true
foo(true); //false
foo(true); //true
foo(true); //false

Confused?

Hi,


var foo = (function(val) {
        alert(val);
        return function() {
        return val = !val;
    };
})(false);

the outer function is just triggered before you call foo
so you can’t pass the parameter.

Ok That seems ok to understand but what do you suggest as an alternative? I want to retain a value from outside a function, shall I just go back to creating it as an attribute of an object?


var foo = (function() {
        var val;
	return function(newval) {
		return val = newval;
	};
})();