How to create in JS a variable equivalent to a static variable in PHP?

0
function cambiarPropiedades(elemento){
        if(typeof control === "undefined"){
            control = true; //No puedo usar el operador var
        }
        if(control == true){
            //Código a ejecutar
            control = false;
        } else {
            //Otro código a ejecutar
            control = true;
        }
    }

I can not use the operator var when defining control because the code does not work because it creates a variable of local scope, and therefore, every time the function is executed and dies, it dies with it the variable and its value, so it would always enter the first if and the result would always be the same. I remember that when I gave some basic brush strokes in PHP they explained to me and I touched a bit the operator static , which allowed to define a variable that is not destroyed when the function dies.

Is there any way to do something equivalent? In the example you can see that I have chosen to declare the variable control as a global variable but I would like it not to be so, to avoid problems and out of pure curiosity. Nor does it convince me to call it _control to indicate its local scope and differentiate it. Is it possible?

    
asked by Adrià Fàbrega 26.11.2017 в 13:44
source

1 answer

1

Try using function cache or memoization . Like everything in object javascript, you can add a property to the functions in execution and use them as cache :

function cambiarPropiedades(elemento){
	if(cambiarPropiedades.control == true){
		//Código a ejecutar
		cambiarPropiedades.control = false;
    console.log("control=true");
	} else {
		//Otro código a ejecutar
		cambiarPropiedades.control = true;
    console.log("control=false");
	}
}

cambiarPropiedades.control = true;
cambiarPropiedades({});

cambiarPropiedades.control = false;
cambiarPropiedades({});

So then you have a variable that does not delete the reference when the execution of the function is finished and it is not global.

    
answered by 27.11.2017 / 00:59
source